Course contentsShow
← Java
Lesson 897 of 2,87021. Generics FundamentalsFree lesson

Cannot Create Generic Arrays

Learning why new T[10] or new ArrayList<String>[5] are illegal due to erasure breaking array covariance and type safety.

Cannot Create Generic Arrays

What you'll learn: Why Java forbids creating arrays of generic types like new T[10] or new ArrayList<String>[5].


The Core Problem

Java doesn't allow you to create arrays of generic types. You cannot write new T[10] inside a generic class, nor can you write new ArrayList<String>[5] anywhere. This restriction exists because of type erasure combined with how arrays enforce type safety.

Why Arrays and Generics Don't Mix

Arrays in Java are covariant and reified—they remember their component type at runtime and check every element assignment. For example, an array created as String[] knows it holds strings and will throw an exception if you try to store an Integer.

Generics use type erasure—the type parameter disappears at runtime. An ArrayList<String> becomes just ArrayList in bytecode.

Here's the conflict: if you could create new ArrayList<String>[5], erasure would turn it into new ArrayList[5] at runtime. The array would think it holds ArrayList (raw type), allowing you to insert ArrayList<Integer> into a spot meant for ArrayList<String>. Later, when you pull out an element expecting strings, you'd get a ClassCastException—exactly what generics are supposed to prevent!

The Analogy

Think of arrays as security guards checking IDs at the door (runtime). Generics are like honor-system guest lists that get shredded after the party starts (type erasure). Combining them creates a security hole where the guard thinks everyone's name is just "Guest."

What You Can Do Instead

Use collections: List<T> or ArrayList<T> instead of T[]. If you absolutely need an array, create an Object[] and cast carefully, accepting compiler warnings.

Key Takeaway: Java prohibits generic array creation because type erasure would let runtime array checks become inconsistent with compile-time generic type safety, breaking the entire type system.