【The Java™ Tutorials】【Generics】3. 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.

如何定义泛型方法:

public class Util {
    public static  boolean compare(Pair p1, Pair p2) {
        return p1.getKey().equals(p2.getKey()) &&
               p1.getValue().equals(p2.getValue());
    }
}

public class Pair {

    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; }
}

如何调用泛型方法:

Pair p1 = new Pair<>(1, "apple");
Pair p2 = new Pair<>(2, "pear");
boolean same = Util.compare(p1, p2);

上面的例子中,我们显式提供了类型,但是,我们也可以不这么做,而是让编译器自己去推断类型:

Pair p1 = new Pair<>(1, "apple");
Pair p2 = new Pair<>(2, "pear");
boolean same = Util.compare(p1, p2);

关于类型推断,后面会有单独的章节来详细讲解。

你可能感兴趣的:(【The Java™ Tutorials】【Generics】3. Generic Methods)