Java Generics-다중 경계

유형 매개 변수는 여러 경계를 가질 수 있습니다.

통사론

public static <T extends Number & Comparable<T>> T maximum(T x, T y, T z)

어디

  • maximum − 최대 값은 일반적인 방법입니다.

  • T− 제네릭 메소드에 전달 된 제네릭 유형 매개 변수. 어떤 Object도 취할 수 있습니다.

기술

T는 일반 클래스 Box에 전달되는 유형 매개 변수이며 Number 클래스의 하위 유형이어야하며 Comparable 인터페이스를 구현해야합니다. 클래스가 바운드로 전달되는 경우 인터페이스 전에 먼저 전달되어야합니다. 그렇지 않으면 컴파일 시간 오류가 발생합니다.

예

원하는 편집기를 사용하여 다음 Java 프로그램을 만듭니다.

package com.tutorialspoint;

public class GenericsTester {
   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 ));
   }

   public static <T extends Number 
      & Comparable<T>> T maximum(T x, T y, T z) {
      T max = x;      
      if(y.compareTo(max) > 0) {
         max = y;   
      }

      if(z.compareTo(max) > 0) {
         max = z;                    
      }
      return max;      
   }

   // Compiler throws error in case of below declaration
   /* public static <T extends Comparable<T> 
      & Number> T maximum1(T x, T y, T z) {
      T max = x;      
      if(y.compareTo(max) > 0) {
         max = y;   
      }

      if(z.compareTo(max) > 0) {
         max = z;                    
      }
      return max;   
   }*/
}

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

산출

Max of 3, 4 and 5 is 5

Max of 6.6,8.8 and 7.7 is 8.8