有时您可能想限制参数的类型,如对数字进行操作的方法可能只希望接受Number或其子类的,这就是有界类型参数的用途,使用extends实现。
这个示例是泛型方法,返回三个Comparable对象中的最大对象-
public class MaximumTest { //确定三个 Comparable 对象中最大的一个 public static <T extends Comparable<T>> T maximum(T x, T y, T z) { T max = x; //假设 x 最初是最大的 if(y.compareTo(max) > 0) { max = y; //y 是迄今为止最大的 } if(z.compareTo(max) > 0) { max = z; //z现在是最大的 } return max; //返回最大的对象 } 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
参考链接
https://www.learnfk.com/java-generics/java-generics-bounded-type.html