泛型方法和有界类型参数
有界的类型参数是实现通用算法的关键。考虑以下方法,该方法计算数组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
,double
,long
,float
,byte
和char
,因此无法编译。您不能使用\>
运算符比较对象。若要解决此问题,请使用以Comparable\<T\>
interface为边界的类型参数:
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;
}