之前只是知道在 Java 中不能創建泛型數組,今天翻看 《Effective Java》其中對這個部分有講解,記錄一下。
現在我們假設在 Java 中可以創建泛型數組,看看可能會發生什么情況:
// 假設可以創建泛型數組 List<String>[] stringLists = new ArrayList<String>[1]; List<Integer> intList = Arrays.asList(42); // 泛型擦除,List 繼承自 Object,所以可以如此賦值 // 在數組中,子類數組 是 父類數組 的子類,Object[] o = new ArrayList[1]; Object[] objects = stringLists; // 同理,泛型擦除后,List 類型變量賦值給 Object 類型變量 // 但此時出現問題了,**** List<Integer> 實例添加到了聲明為 List<String>[] 類型的數組中了 ****** objects[0] = intList; String s = stringLists[0].get(0);
由於泛型擦除,結果就是泛型的檢查作用失效,可以將 List<Integer> 類型的值添加到 List<String>[] 類型的數組中。
而這類問題在編譯時無法發現,只能在運行時出現問題
所以如果禁止創建泛型數組,就可以避免此類問題
另:
public class Main { static class A {} static class B extends A {} public static void main(String[] args) { A[] arraya = new A[5]; B[] arrayb = new B[5]; // 可以正常賦值,B[] 是 A[] 的子類 arraya = arrayb; List<A> lista = new ArrayList<A>(); List<B> listb = new ArrayList<B>(); // lista = listb 編譯錯誤,List<B> 不是 List<A> 的子類 } }