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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With