Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic type for Arraylist of Arraylists

In normal array list initialization, We used to define generic type as follows,

List<String> list1 = new ArrayList<String>();

But in case of ArrayList of ArrayLists, How can we define its generic type?

The code for array list of array lists is as follows:

ArrayList[] arr=new ArrayList[n];
 for(int i=0;i<n;i++)
 {
 arr[i]=new ArrayList();
 } 

Just share the syntax, if anybody have idea about it..!

like image 277
Rajaprabhu Aravindasamy Avatar asked Feb 29 '12 10:02

Rajaprabhu Aravindasamy


2 Answers

You can simply do

List<List<String>> l = new ArrayList<List<String>>();

If you need an array of Lists, you can do

List<String>[] l = new List[n];

and safely ignore or suppress the warning.

like image 110
Daniel Lubarov Avatar answered Oct 29 '22 02:10

Daniel Lubarov


If you (really) want a list of lists, then this is the correct declaration:

List<List<String>> listOfLists = new ArrayList<List<String>>();

We can't create generic arrays. new List<String>[0] is a compiletime error.

like image 27
Andreas Dolk Avatar answered Oct 29 '22 02:10

Andreas Dolk