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发行说明。
Generic methods are methods that introduce their own type parameters. 泛型方法是引入自己类型参数的方法。This is similar to declaring a generic type, but the type parameter's scope is limited to the method where it is declared. 这类似于声明泛型类型,但类型参数的作用域仅限于声明它的方法。Static and non-static generic methods are allowed, as well as generic class constructors.允许使用静态和非静态泛型方法以及泛型类构造函数。
The syntax for a generic method includes a list of type parameters, inside angle brackets, which appears before the method's return type. 泛型方法的语法包括尖括号内的类型参数列表,该列表显示在方法的返回类型之前。For static generic methods, the type parameter section must appear before the method's return type.对于静态泛型方法,类型参数部分必须出现在方法的返回类型之前。
The Util class includes a generic method, compare, which compares two Pair objects:Util类包括一个通用方法compare,它比较两个Pair对象:
public class Util { public static <K, V> boolean compare(Pair<K, V> p1, Pair<K, V> p2) { return p1.getKey().equals(p2.getKey()) && p1.getValue().equals(p2.getValue()); } } public class Pair<K, V> { private K key; private V value; public Pair(K key, V value) { this.key = key; this.value = value; } public void setKey(K key) { this.key = key; } public void setValue(V value) { this.value = value; } public K getKey() { return key; } public V getValue() { return value; } }
The complete syntax for invoking this method would be:调用此方法的完整语法为:
Pair<Integer, String> p1 = new Pair<>(1, "apple"); Pair<Integer, String> p2 = new Pair<>(2, "pear"); boolean same = Util.<Integer, String>compare(p1, p2);
The type has been explicitly provided, as shown in bold. 类型已显式提供,如粗体所示。Generally, this can be left out and the compiler will infer the type that is needed:通常,这可以忽略,编译器将推断出所需的类型:
Pair<Integer, String> p1 = new Pair<>(1, "apple"); Pair<Integer, String> p2 = new Pair<>(2, "pear"); boolean same = Util.compare(p1, p2);
This feature, known as type inference, allows you to invoke a generic method as an ordinary method, without specifying a type between angle brackets. 此功能称为类型推断,允许您将泛型方法作为普通方法调用,而无需在尖括号之间指定类型。This topic is further discussed in the following section, Type Inference.本主题将在下一节类型推断中进一步讨论。