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

Cannot Create Arrays of Parameterized Types

Discover why 'new ArrayList<String>[10]' fails due to array covariance conflicting with generic type safety guarantees.

Cannot Create Arrays of Parameterized Types

What you'll learn: Why new ArrayList<String>[10] is illegal in Java and how it relates to array covariance versus generic type safety.

The Problem with Generic Arrays

You cannot create arrays of parameterized types in Java. This means expressions like new ArrayList<String>[10] or new List<Integer>[5] are compile-time errors.

The reason lies in a fundamental clash between two Java features:

  1. Array covariance: Java arrays are covariant, meaning String[] is a subtype of Object[]. You can assign a String[] to an Object[] variable.

  2. Generic type erasure: At runtime, ArrayList<String> and ArrayList<Integer> both become just ArrayList due to type erasure.

Why the Restriction Exists

Imagine if Java allowed new ArrayList<String>[10]:

// This is ILLEGAL and won't compile
ArrayList<String>[] stringLists = new ArrayList<String>[10];

// But if it did compile, array covariance would let us do:
Object[] objects = stringLists;

// Then we could sneak in the wrong type:
objects[0] = new ArrayList<Integer>(); // Looks like Object[] holding ArrayList

// Now we have an ArrayList<Integer> where we expect ArrayList<String>
stringLists[0].add("Hello"); // Runtime disaster!

Because arrays know their component type at runtime but generics don't (type erasure), the JVM couldn't catch this violation. The array would only know it holds ArrayList objects, not which kind of ArrayList.

The Workaround

Use collections of collections instead:

ArrayList<ArrayList<String>> listOfLists = new ArrayList<>();

Key Takeaway: Java prohibits creating arrays of parameterized types because array covariance combined with generic type erasure would allow type-unsafe operations that the runtime couldn't detect, breaking the compile-time safety guarantees generics provide.