GotchaDifficulty: Advanced1 min

Why You Cannot Write new T[]

A generic class that needs an array of its own type parameter. The line looks unremarkable and the compiler refuses it outright.

java
class Box<T> {
    private T[] items = new T[10];
}
text
Box.java:2: error: generic array creation

T is gone by the time the program runs, and creating an array needs a real type at that moment — an array carries its element type with it and checks every write against it. There is nothing to carry.

What else erasure makes impossible on a type parameter
WrittenWhy it is refused
new T[10]Array creation needs a type that still exists at runtime
new T()There is no class to instantiate
x instanceof TNothing to test against
T.classThere is no class literal for something erased
catch (T e)The handler is matched by type at runtime

The practical answer is almost always to use a collection instead. List<T> works because a list stores Object references and the compiler inserts the casts, which is exactly what an array cannot do.

java
class Box<T> {
    private final List<T> items = new ArrayList<>();
}