类型参数可以具有多个边界。
Multiple Bounds - 语法
public static <T extends Number & Comparable<T>> T maximum(T x, T y, T z)
maximum - 是一种泛型方法。
T - 传递的参数,它可以带任何对象。
T是传递给泛型类Box的类型参数,并且应该是Number类的子类型,并且必须包含Comparable接口。
package com.learnfk; 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 <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; } //编译器在以下声明的情况下抛出错误 /* 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
参考链接
https://www.learnfk.com/java-generics/java-generics-multiple-bounds.html