Java Generics-바인딩 된 유형 매개 변수

유형 매개 변수에 전달할 수있는 유형의 종류를 제한하려는 경우가있을 수 있습니다. 예를 들어, 숫자에 대해 작동하는 메서드는 Number 또는 해당 하위 클래스의 인스턴스 만 허용하려고 할 수 있습니다. 이것이 경계 유형 매개 변수의 용도입니다.

경계 유형 매개 변수를 선언하려면 유형 매개 변수의 이름, extends 키워드, 상위 경계를 차례로 나열하십시오.

예

다음 예제는 "extends"(클래스에서와 같이) 또는 "implements"(인터페이스에서와 같이)를 의미하는 일반적인 의미에서 extends가 사용되는 방법을 보여줍니다. 이 예제는 세 개의 Comparable 객체 중 가장 큰 것을 반환하는 Generic 메서드입니다.

public class MaximumTest {
   // determines the largest of three Comparable objects
   
   public static <T extends Comparable<T>> T maximum(T x, T y, T z) {
      T max = x;   // assume x is initially the largest
      
      if(y.compareTo(max) > 0) {
         max = y;   // y is the largest so far
      }
      
      if(z.compareTo(max) > 0) {
         max = z;   // z is the largest now                 
      }
      return max;   // returns the largest object   
   }
   
   public static void main(String args[]) {
      System.out.printf("Max of %d, %d and %d is %d\n\n", 
         3, 4, 5, maximum( 3, 4, 5 ));

      System.out.printf("Max of %.1f,%.1f and %.1f is %.1f\n\n",
         6.6, 8.8, 7.7, maximum( 6.6, 8.8, 7.7 ));

      System.out.printf("Max of %s, %s and %s is %s\n","pear",
         "apple", "orange", maximum("pear", "apple", "orange"));
   }
}

이것은 다음 결과를 생성합니다-

산출

Max of 3, 4 and 5 is 5

Max of 6.6,8.8 and 7.7 is 8.8

Max of pear, apple and orange is pear