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?

3
  • exact duplicate of stackoverflow.com/questions/4549192/… Commented Jun 20, 2012 at 5:11
  • I can not have ArrayList<ArrayList<MyClass>> Commented Jun 20, 2012 at 5: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<MyClass>[2]; to new ArrayList[2]; it will work but you will get warning. Not that I am recommending it though. Commented Jun 20, 2012 at 5:18

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

As a rule, though, avoid mixing generics and arrays. Prefer List<E> instead of arrays when dealing with generics.
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>>

Comments

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>();

1 Comment

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
0

You can use

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.