Java泛型 - 有界型別引數



有時您可能希望限制允許傳遞給型別引數的型別的種類。例如,對數字進行操作的方法可能只想接受Number或其子類的例項。這就是有界型別引數的用途。

要宣告有界型別引數,請列出型別引數的名稱,後跟extends關鍵字,然後是其上界。

示例

以下示例說明了extends如何在一般意義上表示“擴充套件”(如類)或“實現”(如介面)。此示例是返回三個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
廣告