Java – How do I initialize my generic array?

How do I initialize my generic array?… here is a solution to the problem.

How do I initialize my generic array?

I want an array of ArrayLists:

ArrayList<MyClass>[] myArray;

I want to initialize it with the following code :

myArray = new ArrayList<MyClass>[2];

But I get this error :

Cannot create a generic array of ArrayList<MyClass>

How do I initialize it?

Solution

This is strictly impossible in Java and has not been seen since its implementation.

You can solve it like this :

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

This may (actually, it should) generate a warning, but there is no other way to bypass it. Honestly, you’d better create an ArrayList: of an ArrayList

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

The latter is what I recommend.

Related Problems and Solutions