通用方法和有界类型参数
原文: https://docs.oracle.com/javase/tutorial/java/generics/boundedTypeParams.html
有界类型参数是通用算法实现的关键。考虑以下方法,计算数组T []中大于指定元素elem的元素数。
public static <T> int countGreaterThan(T[] anArray, T elem) {int count = 0;for (T e : anArray)if (e > elem) // compiler error++count;return count;}
该方法的实现很简单,但它不能编译,因为大于运算符(> )仅适用于原始类型,如short , int ,双,长,漂浮,字节和char 。你不能使用>运算符来比较对象。要解决此问题,请使用由Comparable< T>界定的类型参数。接口:
public interface Comparable<T> {public int compareTo(T o);}
生成的代码将是:
public static <T extends Comparable<T>> int countGreaterThan(T[] anArray, T elem) {int count = 0;for (T e : anArray)if (e.compareTo(elem) > 0)++count;return count;}
