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:
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
ArrayListofArrayLists:The latter is what I would recommend.