Java Generics 简明教程

Java Generics - No Array

不允许有参数化类型的数组。

Arrays of parameterized types are not allowed.

//Cannot create a generic array of Box<Integer>
Box<Integer>[] arrayOfLists = new Box<Integer>[2];

由于编译器使用类型擦除,因此类型参数将替换为 Object,并且用户可以向数组中添加任何类型的对象。并且在运行时,代码将不能抛出 ArrayStoreException。

Because compiler uses type erasure, the type parameter is replaced with Object and user can add any type of object to the array. And at runtime, code will not able to throw 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>();