类型参数可以有多个边界。
语法
public static <T extends Number & Comparable<T>> T maximum(T x, T y, T z)
在上面代码中,
- maximum - 最大值是一种通用方法。
- T - 通用类型参数传递给泛型方法。 它可以采取任何对象。
描述
T是传递给泛型类的类型参数应该是Number
类的子类型,并且必须包含Comparable
接口。 如果一个类作为绑定传递,它应该在接口之前先传递,否则编译时会发生错误。
示例
使用您喜欢的编辑器创建以下java程序,并保存到文件:MultipleBounds.java 中,代码如下所示 -
package com.yiibai
public class MultipleBounds {
public static void main(String[] args) {
System.out.printf("Max of %d, %d and %d is %d\n\n", 30, 24, 15,
maximum(30, 24, 15))
System.out.printf("Max of %.1f,%.1f and %.1f is %.1f\n\n", 16.6, 28.8,
17.7, maximum(16.6, 28.8, 17.7))
}
public static <T extends Number & Comparable<T>> 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 <T extends Comparable<T> & 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 }
*/
}
执行上面代码,得到以下结果 -
Max of 30, 24 and 15 is 30
Max of 16.6,28.8 and 17.7 is 28.8