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

Generic Array Creation Restrictions

Learn why you cannot create arrays of parameterized types and explore workarounds for this limitation.

Generic Array Creation Restrictions

What you'll learn: Why Java prohibits creating arrays of parameterized types and how to work around this limitation.


The Core Problem

Java does not allow you to create arrays of parameterized generic types. This means expressions like new T[10] or new ArrayList<String>[5] will not compile.

The reason lies in type erasure—Java's implementation of generics. At runtime, generic type information is removed, so an ArrayList<String> and ArrayList<Integer> both become just ArrayList. Arrays, however, do retain their component type at runtime and perform runtime type checks when storing elements. This creates an incompatibility: the array needs runtime type information that generics cannot provide.

What You Cannot Do

// These will NOT compile:
// T[] array = new T[10];           // Cannot create array of type parameter
// List<String>[] lists = new ArrayList<String>[5];  // Cannot create array of parameterized type

The Workaround

Use an Object array and cast it (with a warning), or use collections instead:

// Approach 1: Array of Object, cast carefully
Object[] internalArray = new Object[10];
// Use with caution, type safety not guaranteed

// Approach 2: Use ArrayList instead
ArrayList<String> collection = new ArrayList<>();
// Collections don't have this restriction

Key Takeaway: Java prevents generic array creation because type erasure removes runtime type information that arrays need for type checking; prefer collections like ArrayList over arrays when working with generics, or use Object[] with careful casting as a last resort.