public class 泛型方法 { publicstaticvoidmain(String[] args) { System.out.println(getMiddle(1, 2, 3)); System.out.println(getMiddle("Wwh", "is", "handsome")); } publicstatic <T> T getMiddle(T ...a) { return a[a.length / 2]; } }
注意,类型变量符放在修饰符后(这个例子中是在static后),并在返回类型前面。
8.4 类型变量的限定
在8.3中撰写的方法,并没有指定对应的类型,所有无论传入什么它都会返回
有时我们需要指定传入的类型的泛型,这时可以使用<T extends Comparable>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
public class 泛型类型变量限定 { publicstaticvoidmain(String[] args) { System.out.println(max(1, 2, 3)); System.out.println(max(1.1, 2.2, 3.3)); }
publicstatic <T extendsComparable> T max(T ...a) { Tlargest= a[0]; for (T t : a) { if (t.compareTo(largest) > 0) { largest = t; } } return largest; } }