我有一个返回整数列表的函数
public List<List<Integer>> threeSum(int[] nums)
显然我无法直接实例化 List,因此我选择使用 ArrayList 并尝试实例化我的返回值,如下所示:
List<List<Integer>> ans = new ArrayList<ArrayList<Integer>>();
上面的方法不起作用,但这个起作用了:
List<List<Integer>> ans = new ArrayList<List<Integer>>();
我的理解是List
是ArrayList继承的接口(interface)。那么,为什么我可以实例化一个列表的 ArrayList 并且没问题,但我无法实例化一个 ArrayList 的 ArrayList?
为了便于阅读,我的函数的前几行如下所示:
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> ans = new ArrayList<List<Integer>>();
if (nums.length < 3) return ans;
最佳答案
这是因为 ArrayList<ArrayList<Integer>>
不是List<List<Integer>>
.
原因是 List<List<Integer>>
您应该能够添加 LinkedList<Integer>
到。但你不能添加 LinkedList<Integer>
到ArrayList<ArrayList<Integer>>
因为它的类型错误。
因此,如果您有 ArrayList<ArrayList<Integer>>
,你永远不能把它当作List<List<Integer>>
,或使用 List<List<Integer>>
类型的变量引用它
关于java - 无法在 Java 中将 ArrayList 的 ArrayList 实例化为列表的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50939292/