Java中具有泛型的有界类型
有时您可能想限制允许传递给类型参数的类型的种类。例如,对数字进行操作的方法可能只希望接受Number或其子类的实例。这就是有界类型参数的用途。
要声明一个有界的类型参数,请列出该类型参数的名称,然后是extends关键字,然后是其上限。
示例
以下示例说明了在一般意义上如何使用扩展来表示“扩展”(如在类中)或“实现”(如在接口中)。这个例子是一个通用方法,返回三个Comparable对象中的最大对象-
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
热门推荐
10 诗词送行祝福语大全简短
11 新房开工吉日祝福语简短
12 50多岁生日简短祝福语
13 安徽疫情祝福语简短英语
14 农民朋友发财祝福语简短
15 对生活祝福语简短精辟
16 搬家词简短祝福语朋友
17 女神结婚快乐祝福语简短
18 文学短句祝福语大全简短