Skip to content Skip to sidebar Skip to footer

How Can I Initialize My Generic Array?

I want to have an array of ArrayLists: ArrayList[] myArray; I want to initialize it by the following code: myArray = new ArrayList[2]; But I get thi

Solution 1:

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.

Solution 2:

As arrays are static in nature and resolved in compile time so you cannot do that instead you can use ArrayList. As

ArrayList<ArrayList<MyClass>>

Solution 3:

You can use

HashMap<some key,ArrayList<MyClass>> or ArrayList<ArrayList<MyClass>>

Post a Comment for "How Can I Initialize My Generic Array?"