泛型方法是引入其本身的类型参数的方法,这相似于声明泛型类型,但类型参数的范围仅限于声明它的方法,容许使用静态和非静态泛型方法,以及泛型类构造函数。segmentfault
泛型方法的语法包括类型参数列表,在尖括号内,它出如今方法的返回类型以前,对于静态泛型方法,类型参数部分必须出如今方法的返回类型以前。app
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; } }
调用此方法的完整语法以下:this
Pair<Integer, String> p1 = new Pair<>(1, "apple"); Pair<Integer, String> p2 = new Pair<>(2, "pear"); boolean same = Util.<Integer, String>compare(p1, p2);
该类型已明确提供,一般,这能够省略,编译器将推断所需的类型:code
Pair<Integer, String> p1 = new Pair<>(1, "apple"); Pair<Integer, String> p2 = new Pair<>(2, "pear"); boolean same = Util.compare(p1, p2);
此功能称为类型推断,容许你将泛型方法做为普通方法调用,而无需在尖括号之间指定类型,本主题将在下一节“类型推断”中进一步讨论。对象