Java-generics-multiple-bounds

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

Javaジェネリック-複数の境界

型パラメーターには複数の境界を設定できます。

構文

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

どこで

  • maximum -最大値は一般的な方法です。
  • T -ジェネリックメソッドに渡されるジェネリック型パラメーター。 任意のオブジェクトを取ることができます。

説明

Tは、ジェネリッククラスBoxに渡される型パラメーターであり、Numberクラスのサブタイプである必要があり、Comparableインターフェイスを実装する必要があります。 クラスがバインドされて渡される場合、インターフェイスの前に最初に渡される必要があります。そうでないと、コンパイル時エラーが発生します。

任意のエディターを使用して、次のJavaプログラムを作成します。

package com.finddevguides;

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