不允許使用參數化類型的數組。如下代碼是錯誤的 -
//Cannot create a generic array of Box<Integer>
Box<Integer>[] arrayOfLists = new Box<Integer>[2];
因為編譯器使用類型擦除,類型參數被替換為Object
,用戶可以向數組添加任何類型的對象。但在運行時,代碼將無法拋出ArrayStoreException
。
// compiler error, but if it is allowed
Object[] stringBoxes = new Box<String>[];
// OK
stringBoxes[0] = new Box<String>();
// An ArrayStoreException should be thrown,
//but the runtime can't detect it.
stringBoxes[1] = new Box<Integer>();
上一篇:
Java泛型不能使用instanceof運算符
下一篇:
Java泛型不能使用異常