Java-generics-bounded-type

提供:Dev Guides
移動先:案内検索

Java Generics-制限された型パラメーター

型パラメータに渡すことができる型の種類を制限したい場合があるかもしれません。 たとえば、数値を操作するメソッドは、Numberまたはそのサブクラスのインスタンスのみを受け入れたい場合があります。 これが境界型パラメータの目的です。

制限された型パラメーターを宣言するには、型パラメーターの名前をリストし、その後にextendsキーワードとその上限をリストします。

次の例は、extends(クラスなど)または「implements」(インターフェイスなど)を意味する一般的な意味でのextendの使用方法を示しています。 この例は、3つのComparableオブジェクトのうち最大のものを返す汎用メソッドです-

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