无法理解如何在java中定义List列表 [英] Not able to understand how to define a List of List in java
问题描述
我想了解两个定义之间的区别以及为什么正确的定义是正确的,错误是错误的。
I want to understand the difference between the two definitions and why the correct one is correct and the wrong is wrong.
显示编译的那个-error
List<List<Integer>> arr2 = new ArrayList<ArrayList<Integer>>();
它给我的错误:
try2.java:8: error: incompatible types: ArrayList<ArrayList<Integer>> cannot be
converted to List<List<Integer>>
List<List<Integer>> arr2 = new ArrayList<ArrayList<Integer>>();
正在运作的那个:
List<ArrayList<Integer>> arr = new ArrayList<ArrayList<Integer>>();
注意:
我理解为什么下面这个有效:
I understand why the below one works:
List<Integer> arr = new ArrayList<Integer>();
编辑-1 :
现在我只想了解 List< List< Integer>>的错误。 arr2 = new ArrayList< ArrayList< Integer>>();
推荐答案
你可以使用钻石操作符,如GhostCat建议的那样,让编译器担心正确的类型。
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>>();
您正在实例化 List
的某些内容(让我们忘记一下,某事恰好是 List< Integer>
),所以你需要创建一个实现列表的类的实例
interface - ArrayList
在这种情况下。所以你创建一个 ArrayList
的实例。
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.
现在,当您想要向您的元素添加元素时列表
,您需要创建一个实现 List< Integer>
的类的实例:
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);
这篇关于无法理解如何在java中定义List列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!