问题
I want to understand the difference between the two definitions and why the correct one is correct and the wrong is wrong.
The one showing me the compile-error
List<List<Integer>> arr2 = new ArrayList<ArrayList<Integer>>();
The error it gave me :
try2.java:8: error: incompatible types: ArrayList<ArrayList<Integer>> cannot be
converted to List<List<Integer>>
List<List<Integer>> arr2 = new ArrayList<ArrayList<Integer>>();
The one which is working:
List<ArrayList<Integer>> arr = new ArrayList<ArrayList<Integer>>();
NOTE:
I understand why the below one works:
List<Integer> arr = new ArrayList<Integer>();
Edit-1:
Now i just want to understand what is wrong with List<List<Integer>> arr2 = new ArrayList<ArrayList<Integer>>();
回答1:
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);
回答2:
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>
.
来源:https://stackoverflow.com/questions/45319323/not-able-to-understand-how-to-define-a-list-of-list-in-java