Java 泛型 - 多重边界
一个类型参数可以有多个边界。
语法
public static <T extends Number & Comparable<T>> T maximum(T x, T y, T z)
Where
maximum − maximum 是一个通用方法。
T − 传递给泛型方法的泛型类型参数。 它可以接受任何对象。
描述
T 是传递给泛型类 Box 的类型参数,应该是 Number 类的子类型,并且必须实现 Comparable 接口。 如果类作为绑定传递,则应在接口之前先传递它,否则会发生编译时错误。
示例
使用您选择的任何编辑器创建以下 java 程序。
package com.tutorialspoint;
public class GenericsTester {
public static void main(String[] args) {
System.out.printf("Max of %d, %d and %d is %d
",
3, 4, 5, maximum( 3, 4, 5 ));
System.out.printf("Max of %.1f,%.1f and %.1f is %.1f
",
6.6, 8.8, 7.7, maximum( 6.6, 8.8, 7.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 3, 4 and 5 is 5 Max of 6.6,8.8 and 7.7 is 8.8

