當你的需要輸入不同類型的參數, 而不需要在使用時轉型
就該使用泛型Generics
原本如果使用Object來控制物件的輸入類型
則會發生輸入類型前後不一致導致runtime error的狀況
改用泛型則可以控制或限定輸入類型
命名公約
E - Element (Collection架構泛用的元素)
K - Key鑑值
N - Number數字
T - Type 類型
V - Value 值
S,U,V etc. - 2nd, 3rd, 4th types 其他順序的Type
基本泛型的使用和實體化
Box<Integer> integerBox = new Box<Integer>();
在Java 7 之後, 後方的參數可以用<>來代替
編譯器會幫忙處理
Box<Integer> integerBox = new Box<>();
Multiple Type Parameters多個參數
public interface Pair<K, V> {
public K getKey();
public V getValue();
}
參數式類型Parameterized Types
OrderedPair<String, Box<Integer>> p = new OrderedPair<>("primes", new Box<Integer>(...));
Raw Types
在泛型的類別可以用原始的物件來設定
平常少用, 可以用一般的寫法就好了
Box<String> stringBox = new Box<>();
Box rawBox = stringBox; // OK
Box rawBox = new Box(); // rawBox is a raw type of Box<T>
Box<Integer> intBox = rawBox; // warning: unchecked conversion
Box<String> stringBox = new Box<>();
Box rawBox = stringBox;
rawBox.set(8); // warning: unchecked invocation to set(T)
1. 官網https://docs.oracle.com/javase/tutorial/java/generics/index.html
2. 簡單例子