The Java™ Tutorials — Generics :Generic Methods and Bounded Type Parameters 泛型方法和受限类型参数
原文地址:https://docs.oracle.com/javase/tutorial/java/generics/boundedTypeParams.html
关键点
- 泛型算法实现的关键:利用受限类型参数
全文翻译
Bounded type parameters are key to the implementation of generic algorithms. Consider the following method that counts the number of elements in an array T[] that are greater than a specified element elem.
受限泛型参数是实现泛型算法的关键。看看下面的方法,它会计算泛型数组中比指定元素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;
}
The implementation of the method is straightforward, but it does not compile because the greater than operator (>) applies only to primitive types such as short, int, double, long, float, byte, and char. You cannot use the > operator to compare objects. To fix the problem, use a type parameter bounded by the
Comparable<T>
interface:
方法的实现非常直接,但编不过。因为大于操作符(>)仅对原始类型如short、int,double、long、float、byte和char有效。你不能用“>”去比较对象。为了搞定这个问题,你需要使用一个受Comparable<T>
接口限定的类型参数。
public interface Comparable<T> {
public int compareTo(T o);
}
The resulting code will be:
代码就改写为了这样:
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;
}