Documentation

The Java™ Tutorials
Hide TOC
Generic Methods泛型方法
Trail: Learning the Java Language
Lesson: Generics (Updated)

Generic Methods泛型方法

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.本主题将在下一节类型推断中进一步讨论。


Previous page: Raw Types
Next page: Bounded Type Parameters