Array of Generic List

You can’t have an array, because an array requires a raw type. You typecast it in the second instance, which makes it fit the defined type, and is therefore legal (however, this is impossible for it to infer). The list of list is legal as ArrayList isn’t an array.

Read chapter 7.3 (page 15) in the official tutorial for more details on this.

The component type of an array object may not be a type variable or a
parameterized type, unless it is an (unbounded) wildcard type.You can
declare array types whose element type is a type variable or a
parameterized type, but not array objects.
This is annoying, to be sure. This restriction is necessary to avoid situations like:

List<String>[] lsa = new List<String>[10]; // not really allowed
Object o = lsa;
Object[] oa = (Object[]) o;
List<Integer> li = new ArrayList<Integer>();
li.add(new Integer(3));
oa[1] = li; // unsound, but passes run time store check
String s = lsa[1].get(0); // run-time error - ClassCastException

If arrays of parameterized type were allowed, the example above would
compile without any unchecked warnings, and yet fail at run-time.

The tutorial then goes on to say the following:

Since type variables don’t exist at run time, there is no way to determine what the
actual array type would be.
The way to work around these kinds of limitations is to use class literals as run time
type tokens

Leave a Comment