How can I initialize my generic array?

android, arraylist, generics, initialization, java

Solution

This is not strictly possible in Java and hasn't been since its implementation.

You can work around it like so:

ArrayList<MyClass>[] lists = (ArrayList<MyClass>[])new ArrayList[2];

This may (really, it should) generate a warning, but there is no other way to get around it. In all honesty, you would be better off to create an `ArrayList` of `ArrayList`s:

ArrayList<ArrayList<MyClass>> lists = new ArrayList<ArrayList<MyClass>>(2);

The latter is what I would recommend.

Problem

I want to have an array of ArrayLists: ``` ArrayList<MyClass>[] myArray; ``` I want to initialize it by the following code: ``` myArray = new ArrayList<MyClass>[2]; ``` But I get this error: ``` Cannot create a generic array of ArrayList<MyClass> ``` How can I initialize it?

Original source

Related problems