Course contentsShow
← Java
Lesson 965 of 2,87022. Generics: Bounds and WildcardsFree lesson

Cannot Create Generic Arrays: T[] vs List<T>

Understand why 'new T[10]' fails within generic classes, and best practices using List<T> or reflection-based solutions.

Cannot Create Generic Arrays: T[] vs List<T>

You'll learn why Java won't let you create arrays of generic types directly, and how to use List<T> as the preferred alternative.

Why new T[10] Fails

Imagine trying to build a box labeled "contains unknown type" and then asking a factory to manufacture 10 of those boxes. The factory needs to know exactly what material to use, but "unknown" isn't specific enough.

In Java, when you write new T[10] inside a generic class, the compiler refuses because type erasure removes T at runtime. Arrays, however, need their component type information at runtime for type checking. This creates an impossible situation: arrays require what generics cannot provide.

public class Container<T> {
    private T[] items; // field declaration is fine
    
    public Container(int size) {
        // this.items = new T[size]; // COMPILE ERROR!
    }
}

The List<T> Solution

Instead of arrays, use List<T>:

public class Container<T> {
    private List<T> items;
    
    public Container(int size) {
        this.items = new ArrayList<>(); // Works perfectly!
    }
    
    public void add(T item) {
        items.add(item);
    }
}

List<T> handles type erasure gracefully because it doesn't need runtime type information the same way arrays do. It provides type safety at compile time while remaining flexible at runtime.

When You Absolutely Need Arrays

If you truly need an array (rare cases), you can use Object[] internally and cast carefully, or pass a Class<T> token for reflection-based creation—but these approaches sacrifice type safety and elegance.

Key Takeaway: You cannot create generic arrays with new T[] due to type erasure conflicts with array runtime type checking; always prefer List<T> for type-safe, flexible generic collections.