3

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?

Bob
  • 22,810
  • 38
  • 143
  • 225
  • exact duplicate of http://stackoverflow.com/questions/4549192/create-an-array-of-arrayliststring-elements – Shahzeb Jun 20 '12 at 05:11
  • I can not have `ArrayList>` – Bob Jun 20 '12 at 05:14
  • When you are on that page , if you hit down arrow you will notice page moving and other answers will appear_magic_ . Having said that choice is more of what you can rather than you want . Any way if you change `new ArrayList[2];` to `new ArrayList[2];` it will work but you will get warning. Not that I am recommending it though. – Shahzeb Jun 20 '12 at 05:18

4 Answers4

4

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.

Cat
  • 66,919
  • 24
  • 133
  • 141
0

You can use

HashMap<some key,ArrayList<MyClass>> or ArrayList<ArrayList<MyClass>>
jaychapani
  • 1,501
  • 1
  • 13
  • 31
0

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>>
Chandra Sekhar
  • 18,914
  • 16
  • 84
  • 125
0

How about this?

ArrayList<String>[] f = (ArrayList<String>[]) Array.newInstance(ArrayList.class, size);


for(int ix = 0; ix < f.length;ix++)
    f[ix] = new ArrayList<String>();
  • `Array.newInstance(ArrayList.class, size)` has no advantage over `new ArrayList[size]`. There is never a point in using `Array.newInstance` with a class literal – newacct Jun 20 '12 at 06:12