Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I initialize my generic array?

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?

like image 333
Bobs Avatar asked May 27 '26 17:05

Bobs


1 Answers

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 ArrayLists:

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

The latter is what I would recommend.

like image 50
Cat Avatar answered May 30 '26 07:05

Cat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!