views:

152

answers:

5

I am new to Java, so I am not aware of the nitty gritties.
Why can't I create generic array of parametrized ArrayList?
Instead I have to write,

ArrayList<String>[] alist = new ArrayList[10]; 

or I have to create List of ArrayLists.
Aren't arrays supposed to be more efficient than ArrayLists? Then why doesn't Java allow it?
Also, what is the difference between following two lines.

ArrayList<String>[] alist = new ArrayList[10];  
ArrayList<String>[] alist = new ArrayList<?>[10];  
+1  A: 

The reason you have to do that is because generics don't really exist in Java. It's actually a compiler hack.

As for the two lines you posted, there shouldn't be any difference in terms of the bytecode produced. However, in the first case you'll probably get a warning because your compiler thinks you forgot java.util.ArrayList wants a type parameter, whereas the latter won't compile because you're trying to instantiate a generic array. Lose-lose situation :(

miorel
+1  A: 

Read chapter 7.3 (page 15) in the official tutorial.

Roman
Thanks Roman. The tutorial is tough to follow at first, but the aspect is explained in detail.
athena
+2  A: 

Actually the implementation of ArrayList is very efficient for read and write actions that don't change the size of the list. In many cases (at least since java 1.6) the compiler will totally remove the method call overhead (for instance for get()).

Also not many programs require the performance that an array offers, so don't worry about using arrays until your code is too slow (and even then you probably don't need the arrays)

Thirler
+2  A: 

If you could do that, this will happen :

ArrayList<String>[] alist = new ArrayList<String>[10];
Object[] olist = alist;   // This is okay because ArrayList is an Object
olist[0] = new ArrayList<Dog>();
olist[0].add(new Dog());
String s = alist[0].get(0);  //Uh oh, Dog is not string
fastcodejava
This a a fundamental flaw in array covariance and is not the reason for the error.
SLaks
+1  A: 

I would also recommend creating an arraylist of arraylists.

ArrayList<ArrayList<Type>> alist = new ArrayList<ArrayList<Type>>();

, where Type is whatever type you wanted the list to be. You now have an arraylist that holds array lists. If you want to add an arraylist, you can do:

alist.add(new ArrayList<Type>());
Leif Andersen
+1 Even better, `List<List<Type>>`, an example of coding to the interface. http://stackoverflow.com/questions/2039549/find-words-in-a-hashset-or-treeset/2040263#2040263
trashgod
I am keen to know, why is creating Lists of Lists is better, rather than just array of lists.
athena