Documentation

The Java™ Tutorials
Hide TOC
Generic Methods and Bounded Type Parameters泛型方法和有界类型参数
Trail: Learning the Java Language
Lesson: Generics (Updated)
Section: Bounded Type Parameters

Generic Methods and Bounded Type Parameters泛型方法和有界类型参数

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.考虑下面的方法,它计算数组T[]中元素大于指定元素elm的数目。

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. 该方法的实现非常简单,但由于使用了大于运算符(>),因此无法编译仅适用于基本类型,如shortintdoublelongfloatbytecharYou cannot use the > operator to compare objects. 您不能使用>运算符来比较对象。To fix the problem, use a type parameter bounded by the Comparable<T> interface:要解决此问题,请使用由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;
}

Previous page: Bounded Type Parameters
Next page: Generics, Inheritance, and Subtypes