开发手册 欢迎您!
软件开发者资料库

Java泛型 - 有界类型参数

Java泛型有界类型参数 - 从简单和简单的步骤学习Java泛型,从基本到高级概念,包括概述,环境设置,通用类,类型参数命名约定,类型推断,多类型参数,参数化类型,原始类型,通用方法,有界类型参数,多个边界,内建类,通用列表,通用集,通用映射,通配符,上限有界通配符,无界通配符,下限有界通配符,通配​​符使用指南,类型擦除,通用类型擦除,通用擦除方法,泛型限制,无原始类型,无实例,无静态字段,无转换,无instanceOf,无数组,无异常,无过载。

有时您可能希望限制允许传递给类型参数的类型.例如,对数字进行操作的方法可能只想接受Number或其子类的实例.这是有界类型参数的用途.

要声明有界类型参数,请列出类型参数的名称,然后是extends关键字,后跟其上限.

示例

以下示例说明了如何在一般意义上使用extends来表示"extends"(如在类中)或"implements"(如在interfaces中).这个例子是Generic方法,用于返回三个Comparable对象中最大的一个 :

public class MaximumTest {   // determines the largest of three Comparable objects      public static > 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 5Max of 6.6,8.8 and 7.7 is 8.8Max of pear, apple and orange is pear