简体   繁体   中英

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..!

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.

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.

Something like this:

List<List<Number>> matrix = new ArrayList<List<Number>>();
for (int i = 0; i < numRows; ++i) {
    List<Number> row = new ArrayList<Number>();
    // add some values into the row
    matrix.add(row);
}

Make the type of the inner List anything you want; this is for illustrative purposes only.

You are talking about an array of lists (ArrayLists to be more specific). Java doesn't allow generic array generation (except when using wildcards, see next paragraph). So you should either forget about using generics for the array, or use a list instead of an array (many solutions proposed for this).

Quote from IBM article :

Another consequence of the fact that arrays are covariant but generics are not is that you cannot instantiate an array of a generic type (new List[3] is illegal), unless the type argument is an unbounded wildcard (new List< ?>[3] is legal).

You are Right: This looks insane. (May its an Bug...) Instead of Using

ArrayList<String>[] lst = new ArrayList<String>[]{};

Use:

ArrayList<String>[] list1 = new ArrayList[]{};

will work for the declaration, even if you dont describe an congrete generic!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM