본문 바로가기

Java

자바의 신 ch.21 제네릭

 

package godOfJava.d.generic.practice;

public class MaxFinder {
  public static void main(String[] args) {
    MaxFinder sample = new MaxFinder();
    sample.testGetMax();
    sample.testGetMin();
  }
  public void testGetMax() {
    System.out.println(getMax(1,2,3));
    System.out.println(getMax(3,1,2));
    System.out.println(getMax(2,3,1));
    System.out.println(getMax("a", "b", "c"));
    System.out.println(getMax("b", "c", "a"));
    System.out.println(getMax("c", "b", "a"));
  }
  public void testGetMin() {
    System.out.println(getMin(1,2,3,4));
    System.out.println(getMin(3,1,2));
    System.out.println(getMin(2,3,1));
    System.out.println(getMin("a", "b", "c"));
    System.out.println(getMin("b", "c", "a"));
    System.out.println(getMin("c", "b", "a"));
  }
  public <T extends Comparable<T>> T getMax(T ... a)
  // You can use a construct called varargs to pass an arbitrary number of values to a method. 
  // You use varargs when you don't know how many of a particular type of argument will be passed to the method. 
  // It's a shortcut to creating an array manually (the previous method could have used varargs rather than an array).
  //To use varargs, you follow the type of the last parameter by an ellipsis (three dots, ...), then a space, and the parameter name. 
  // The method can then be called with any number of that parameter, including none.
  {
    T maxT = a[0];
    for(T tempT : a) {
      if(tempT.compareTo(maxT)>0) maxT = tempT;
    }
    return maxT;
  }

  public <T extends Comparable<T>> T getMin(T ... a) {
    T minT = a[0];
    for(T tempT : a) {
      if(tempT.compareTo(minT)<0) minT = tempT;
    }
    return minT;
  }
}

 

 

제네릭은 아직 익숙하지 않아서, 내일 여러 유튜브 영상을 보며 복습할 예정이다. 

 

 

'Java' 카테고리의 다른 글

자바의 신 ch.23 Collection 2  (0) 2022.05.23
자바의 신 ch.22 collection - List  (0) 2022.05.23
자바의 신 ch.20 자바랭  (0) 2022.05.17
자바의신 1권 마지막  (0) 2022.05.15
자바의 신 ch.16, 17  (0) 2022.05.12