Generic type for Arraylist of Arraylists

2020-02-28 06:13发布

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

5条回答
走好不送
2楼-- · 2020-02-28 06:51

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.

查看更多
够拽才男人
3楼-- · 2020-02-28 06:59

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.

查看更多
迷人小祖宗
4楼-- · 2020-02-28 07:00

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!

查看更多
够拽才男人
5楼-- · 2020-02-28 07:02

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.

查看更多
趁早两清
6楼-- · 2020-02-28 07:11

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

查看更多
登录 后发表回答