【问题标题】:Add List to List<List<>> collections in java [duplicate]将列表添加到 java 中的 List<List<>> 集合 [重复]
【发布时间】:2016-03-24 01:49:10
【问题描述】:
List<List<Integer>> list = new LinkedList<List<Integer>>();
List<Integer> tmp = new LinkedList<Integer>();
tmp.add(2);
list.add(tmp);
tmp.add(3);
list.add(tmp);

列表的结果是[[2,3],[2,3]]; 我只是很困惑为什么它不是[[2],[2,3]]。当我使用list.add(new LinkedList&lt;Integer&gt;(tmp)) 时,它会起作用。我打印tmp,还是[2], [2,3],没变。为什么会这样? 提前谢谢你。

【问题讨论】:

  • 因为 list 的两个元素都指向同一个对象 temp。如果您想要结果 [[2],[2,3]],您可以创建新的另一个 tmp 对象。
  • 在当前代码中,您只实例化了一次tmp,因此将它添加到list 中两次,但它是同一个对象。

标签: java list add


【解决方案1】:

您向list 添加了对tmp 的引用。当您添加它时,tmp 仅包含 [2,3]。添加到list 之后,您将3 添加到tmp 的同一引用中。这导致两个“副本”都有 [2,3]。

一种方法是创建一个新列表并执行以下操作

tmp = new LinkedList<Integer>();
tmp.add(3);
list.add(tmp);

现在,列表看起来像 [[2],[3]]。

如果您希望列表为 [[2],[2,3]]...

List<List<Integer>> list = new LinkedList<List<Integer>>();
List<Integer> tmp = new LinkedList<Integer>();
tmp.add(2);

// add a copy of this linkedlist to the "BIG" list
list.add(new LinkedList<Integer>(tmp));
tmp.add(3);
list.add(tmp);

如果有不清楚的地方请告诉我。

【讨论】:

    【解决方案2】:

    Java 使用对您使用new 创建的对象的引用来引用这些对象。在这个例子中,变量tmp实际上是对堆上LinkedList对象的引用。

    由于list 是一个对象列表,它实际上是对这些对象的引用列表。在这种情况下,它的两个元素是对同一个堆对象tmp 的引用。

    【讨论】:

      猜你喜欢
      • 2018-07-17
      • 2016-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多