【问题标题】:Declare a list with list of lists [duplicate]用列表列表声明一个列表[重复]
【发布时间】:2016-01-02 20:16:51
【问题描述】:
List<List<Integer>> l = new LinkedList<LinkedList<Integer>>();
List<List<Integer>> l2 = new List<LinkedList<Integer>>();
List<List<Integer>> l3 = new LinkedList<List<Integer>();
List<List<Integer>> l4 = new LinkedList<>();

我不明白为什么只有第三和第四个语句有效。

【问题讨论】:

  • 同样的理由你不能做LinkedList&lt;Base&gt; list = new LinkedList&lt;Derived&gt;();
  • 第二个不起作用,因为List 是一个接口。没有实现就不能创建new 接口。
  • 我推荐选项 4,List&lt;List&lt;Integer&gt;&gt; l4 = new LinkedList&lt;&gt;();

标签: java list generics linked-list declaration


【解决方案1】:

第一个声明不起作用,因为 LinkedList&lt;LinkedList&lt;Integer&gt;&gt; 不是 List&lt;List&lt;Integer&gt;&gt;。例如,通过声明,您可以将ArrayList&lt;Integer&gt; 添加到List&lt;List&lt;Integer&gt;&gt;(整数列表列表)。但是,ArrayList&lt;Integer&gt; 无法添加到 LinkedList&lt;LinkedList&lt;Integer&gt;&gt;(整数链表的链表)。

new List开头的第二次初始化不能工作,因为List是一个接口,而不是一个类,所以不能用new操作符初始化。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2015-06-25
  • 1970-01-01
  • 2020-05-02
  • 1970-01-01
  • 1970-01-01
  • 2022-12-24
  • 2013-04-18
  • 2021-07-21
相关资源
最近更新 更多