Not able to understand how to define a List of List in java [duplicate]

蹲街弑〆低调 提交于 2019-12-04 19:46:50

You could use the diamond operator, as GhostCat suggested, and let the compiler worry about the correct type.

But if you want to understand what the correct type should be, use:

List<List<Integer>> arr2 = new ArrayList<List<Integer>>(); 

You are instantiating a List of something (let's forget for a second that something happens to be a List<Integer>), so you need to create an instance of a class that implements the List interface - ArrayList in this case. So you create an instance of ArrayList of something.

The element type (my so called "something") - List<Integer> in your example - remains unchanged.

Now, when you want to add an element to your List, you need to create an instance of a class that implements List<Integer>:

List<Integer> inner = new ArrayList<Integer>();
arr2.add(inner);

You don't need any of that:

List<List<Whatever>> items = new ArrayList<>();

Done.

The important thing to understand: you can not create those "inner" lists. You just create a List (that has type "list of lists"). Later on, you would do:

List<Whatever> innerItems = new ArrayList<>();
items.add(innerItems);

for example. The reason is: collections are not arrays. Java allows you to write down expressions that create a full blown 2-dim array. But collections don't have that concept of multiple dimensions (implementation-wise)!

One part of that is the fact that generics are actually implemented using type erasure. This means: the actual list implementation doesn't know anything about the generic type you used in your source code. It is only dealing with instances of Object. In that sense, it is not possible that the implementation "knows" that the new List is supposed to contain List<Whatever>.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!