Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java question about ArrayList<Integer>[] x

I have always had this one issue with arrays of ArrayLists. Maybe you can help.

//declare in class
private ArrayList<Integer>[] x;

//in constructor
x=new ArrayList[n];

This generates a warning about unchecked conversion.

But

x=new ArrayList<Integer>[n];

is a compiler error.

Any idea?

Thanks!

like image 570
David Robles Avatar asked Mar 11 '11 11:03

David Robles


2 Answers

I think you cannot make array of generic arraylist because no generic information will be available at runtime.Instead you can do like this:

List<Integer>[] arr=new ArrayList[30];
arr[0]=new ArrayList<Integer>();//create new arraylist for every index.
like image 109
Emil Avatar answered Oct 15 '22 08:10

Emil


You can't make a array of generics lists. Fortunately, there are workarounds. And even more fortunately, there is a nice site about Generics with more information than you'd ever want to know. The link goes straight to the Arrays in Java Generics part.

like image 29
extraneon Avatar answered Oct 15 '22 08:10

extraneon