嵌套list的实例化

在LeetCode上遇到这样返回值

public class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
}
}
List<List<Integer>>

即List的内容是List的类型,直接使用List<List<Integer>> list = new List<List<Integer>>()是错的,因为List是接口,不能实例化(Cannot instantiate the type List<List<Integer>>)。

但如果使用 

1 List<List<Integer>> list = new LinkedList<LinkedList<Integer>>(); 

又会报错(cannot convert from LinkedList<LinkedList<Integer>> to List<List<Integer>>),

正确的做法是修改成:

1 List<LinkedList<Integer>> list = new LinkedList<LinkedList<Integer>>();
3 或
5 List<List<Integer>> list = new LinkedList<List<Integer>>();
这样才可以,也就是说,泛型的类型参数必须相同。

下面这种处理

1 ArrayList<ArrayList<String>> list= new ArrayList<ArrayList<String>>();
2 或
3 LinkedList<LinkedList<String>> list = new LinkedList<LinkedList<String>>();
也是可以的,这样就没有用 接口类 引用 实现类 了。

posted @ 2017-07-22 21:33  岁月静好--lyr  阅读(887)  评论(0编辑  收藏  举报