I want to create an Array that contains ArrayList elements.

I've tried ArrayList<String> name[] = new ArrayList<String>()[]; but that doesn't seem to work.

share|improve this question
You want an arraylist of arraylists. Why would you use an array in one sense and an arraylist in others? – Falmarri Dec 28 '10 at 20:25
I know how many elements there will be. Is it still better to use an arraylist of arraylists? – sighol Dec 28 '10 at 20:27
This is a duplicate of: stackoverflow.com/questions/2792731/… – Tom Dec 29 '10 at 4:07
feedback

5 Answers

up vote 14 down vote accepted

You cannot create an array of a generic type.

Instead, you can create an ArrayList<ArrayList<String>>.

share|improve this answer
feedback

The correct way is:

ArrayList<String> name[] = new ArrayList[9];

However, this won't work either, since you can't make an array with a generic type, what you are trying to do is a matrix, and this should be done like this:

String name[][];
share|improve this answer
1  
but the first DOES work, however it shows a type safety warning. – Carlos Heuberger Dec 28 '10 at 21:11
feedback
ArrayList<ArrayList<String>> name= new ArrayList<ArrayList<String>>(/*capacity*/);
share|improve this answer
feedback

If you do want an array of ArrayList, you'll have to initialise each position of the array individually:

int size = 9; // 9 is just an example
// you can remove the annotation, but you'll be warned:
// Type safety: The expression of type ArrayList[] needs unchecked conversion 
// to conform to ArrayList<String>[]
@SuppressWarnings("unchecked")
ArrayList<String> name[] = new ArrayList[ size];
for( int i = 0; i < size; i++) {
    name[ i] = new ArrayList<String>();
}
share|improve this answer
feedback

This is not proper OO and this sort of code is very implementation coupled. If you need to do such thing, probably you did something wrong. If the code is not yours, the person who made it probably did something wrong.

If you know how many elements are there (or even if you didn't), why not use Map<Integer, List<String>>?

share|improve this answer
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.