views:

156

answers:

3

Dupe: http://stackoverflow.com/questions/185594/java-generics-syntax-for-arrays

I want to create an array that will hold linked lists of Integer type..

import java.util.LinkedList;

public class Test {

    public static void main(String [] args){

     LinkedList<Integer> [] buckets = new LinkedList<Integer>[10];  

    }
}

I get an error saying: Cannot create a generic array of LinkedList

Why is this? Can it be solved?

+4  A: 

Generics and ye olde arrays don't get on well (this subject has been done to death meny times, here and elsewhere). Use an (array) list of lists.

Tom Hawtin - tackline
+1 for 'ye olde'
bedwyr
+1  A: 

You could wrap it with another list type, e.g:

ArrayList<LinkedList<Integer>> buckets = new ArrayList<LinkedList<Integer>>();
Chris Thornhill
+1  A: 

try

List<Integer> [] buckets = new LinkedList[10];

I don't know why Java doesn't allow generics on arrays given you can just drop the generic on the right (though it will give an unchecked warning this way)

Peter Lawrey
its because arrays are reified (runtine behavior) and generics uses type erasure at compiletime
Schildmeijer
I don't see why the compile cannot check the generics types match, and otherwise treat it as if it wasn't there.
Peter Lawrey