泛型方法是引入其本身的類型參數的方法,這相似於聲明泛型類型,但類型參數的範圍僅限於聲明它的方法,容許使用靜態和非靜態泛型方法,以及泛型類構造函數。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);
此功能稱爲類型推斷,容許你將泛型方法做爲普通方法調用,而無需在尖括號之間指定類型,本主題將在下一節「類型推斷」中進一步討論。對象