Java泛型 - 多重界限( Multiple Bounds)
类型参数可以有多个边界。
语法 (Syntax)public static > T maximum(T x, T y, T z)
哪里maximum - maximum是一种通用方法。
T - 传递给泛型方法的泛型类型参数。 它可以采取任何对象。
描述 (Description)
T是传递给泛型类Box的类型参数,应该是Number类的子类型,并且必须包含Comparable接口。 如果一个类以绑定方式传递,则应在接口之前首先传递它,否则将发生编译时错误。
例子 (Example)
使用您选择的任何编辑器创建以下Java程序。package com.iowiki;
public class GenericsTester {
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 ));
}
public static
& Comparable> T maximum(T x, T y, T z) {
T max = x;
if(y.compareTo(max) > 0) {
max = y;
}
if(z.compareTo(max) > 0) {
max = z;
}
return max;
}
// Compiler throws error in case of below declaration
/* public static
& Number> T maximum1(T x, T y, T z) {
T max = x;
if(y.compareTo(max) > 0) {
max = y;
}
if(z.compareTo(max) > 0) {
max = z;
}
return max;
}*/
}
这将产生以下结果 -
输出 (Output)Max of 3, 4 and 5 is 5
Max of 6.6,8.8 and 7.7 is 8.8
有界类型参数(Bounded Type Parameters)