The Java Tutorials have been written for JDK 8.Java教程是为JDK 8编写的。Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available.本页中描述的示例和实践没有利用后续版本中引入的改进,并且可能使用不再可用的技术。See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.有关Java SE 9及其后续版本中更新的语言特性的摘要,请参阅Java语言更改。
See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.有关所有JDK版本的新功能、增强功能以及已删除或不推荐的选项的信息,请参阅JDK发行说明。
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. 该方法的实现非常简单,但由于使用了大于运算符(>),因此无法编译仅适用于基本类型,如short、int、double、long、float、byte和char。You 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; }