Java 泛型无数组

创建于 2024-12-02 / 32
字体: [默认] [大] [更大]

不允许使用参数化类型的数组。

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


0 人点赞过