Java泛型有界类型参数
下文笔者讲述java泛型参数类型的界限限定的方法分享,如下所示:
在java泛型中,有时候我们需限制泛型的类型,那么该如何操作呢? 下文笔者将一一道来,如下所示: 如:对数字进行操作的方法可能只想接受Number或其子类的实例 我们将这种限定称之为“有界的类型参数” 实现思路: 有界类型需使用extends关键字例:
public class MaximumTest {
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
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


