標籤:聲明 key log type pre integer erb rabl ret
泛型基礎
泛型類
我們首先定義一個簡單的Box類:
public class Box { private String object; public void set(String object) { this.object = object; } public String get() { return object; }}
這是最常見的做法,這樣做的一個壞處是Box裡面現在只能裝入String類型的元素,今後如果我們需要裝入Integer等其他類型的元素,還必須要另外重寫一個Box,代碼得不到複用,使用泛型可以很好的解決這個問題。
public class Box<T> { // T stands for "Type" private T t; public void set(T t) { this.t = t; } public T get() { return t; }}
這樣我們的Box類便可以得到複用,我們可以將T替換成任何我們想要的類型:Box<Integer> integerBox = new Box<Integer>();Box<Double> doubleBox = new Box<Double>();Box<String> stringBox = new Box<String>();
泛型方法 看完了泛型類,接下來我們來瞭解一下泛型方法。聲明一個泛型方法很簡單,只要在傳回型別前面加上一個類似<K, V>的形式就行了: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; }}
我們可以像下面這樣去調用泛型方法:Pair<Integer, String> p1 = new Pair<>(1, "apple");Pair<Integer, String> p2 = new Pair<>(2, "pear");boolean same = Util.<Integer, String>compare(p1, p2);
邊界符
現在我們要實現這樣一個功能,尋找一個泛型數組中大於某個特定元素的個數,我們可以這樣實現:
public interface Comparable<T> { public int compareTo(T o);}public static <T extends Comparable<T>> int countGreaterThan(T[] anArray, T elem) { int count = 0; for (T e : anArray) if (e.compareTo(elem) > 0) ++count; return count;}
java泛型介紹