Home >Java >javaTutorial >Why Can\'t I Create an Array of Generic Lists in Java?
Generic Arrays and the Mystery of Type Erasure
When working with generics, it can be confusing why some array declarations are allowed and others aren't. Consider the following:
ArrayList<Key> a = new ArrayList<Key>(); // Compiles fine
This code compiles without issue. However, when it comes to arrays of generic lists:
ArrayList<Key>[] a = new ArrayList<Key>[10]; // Compiler error
the compiler complains. Why is this the case?
The Role of Type Erasure
This issue stems from the concept of type erasure in Java. When a generic type is compiled, its type parameters are removed and replaced with raw types. This means that at runtime, all generic types are treated as their corresponding raw types.
In the first example, ArrayList
However, an array is a different story. Each element of an array must have the same type. So, ArrayList
Fixing the Issue
To fix the issue, one can cast the array to an explicit raw type:
ArrayList<Key>[] a = (ArrayList<Key> []) new ArrayList[10];
This cast essentially tells the compiler that we want an array of raw ArrayList objects, which is a valid type.
Using Nested Lists
Another option is to use a list of lists:
ArrayList<ArrayList<Key>> b = new ArrayList<ArrayList<Key>>();
In this case, b is a list of ArrayList objects, where each ArrayList can hold elements of type Key. This approach is legal because ArrayList isn't an array type.
Additional Information
For further insights into this topic, refer to Chapter 7.3 of the official Java tutorial. It explains how array types cannot have type variables as their components, unless they are wildcard types.
The above is the detailed content of Why Can\'t I Create an Array of Generic Lists in Java?. For more information, please follow other related articles on the PHP Chinese website!