Java 泛型 - 沒有陣列



不允許使用引數化型別的陣列。

//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>();  
廣告