【问题标题】:Adding elements to List<List<String>> from an array list从数组列表向 List<List<String>> 添加元素
【发布时间】:2016-06-03 12:03:01
【问题描述】:

我想将数据副本添加到我的列表中,但是当我使用 .add 时,它会添加引用而不是副本。我会尽力解释我的意思。

    List<List<String>> formattedTempMatches = new ArrayList<>();
    ArrayList<String> rowFormattedMatches = new ArrayList<>();
    rowFormattedMatches.add(matchesArray[0]);
    rowFormattedMatches.add(matchesArray[1]);
    rowFormattedMatches.add(matchesArray[2]);
    formattedTempMatches.add(rowFormattedMatches);
    //rowFormattedMatches.clear();
    rowFormattedMatches.add(matchesArray[3]);
    rowFormattedMatches.add(matchesArray[4]);
    rowFormattedMatches.add(matchesArray[5]);
    formattedTempMatches.add(rowFormattedMatches);

我在循环之外编写了我的代码,试图更好地解释自己。我想将 3 个元素添加到 ArrayList(其中元素来自普通数组),然后将该 ArrayList 添加到列表列表中。当 ArrayList 添加到列表中时,我想清除它并用另外 3 个元素重新填充它,然后将其添加到列表的下一个索引中。问题是一旦我清除它,数据就会从列表中删除。如果我不清除它,列表在每个索引处有 6 个元素,而应该只有 3 个。我该怎么办?

对我可能令人困惑的解释深表歉意。

【问题讨论】:

  • 尝试使用formattedTempMatches.add((ArrayList)rowFormattedMatches.clone());

标签: java arrays list arraylist


【解决方案1】:

clear() 的调用会清空列表。由于您为每次迭代使用相同的实例,因此这将不起作用。除了清除列表之外,您可以做的是创建一个新实例:

List<List<String>> formattedTempMatches = new ArrayList<>();
ArrayList<String> rowFormattedMatches = new ArrayList<>();
rowFormattedMatches.add(matchesArray[0]);
rowFormattedMatches.add(matchesArray[1]);
rowFormattedMatches.add(matchesArray[2]);
formattedTempMatches.add(rowFormattedMatches);
rowFormattedMatches = new ArrayList<>(); // new instance of an empty list
rowFormattedMatches.add(matchesArray[3]);
rowFormattedMatches.add(matchesArray[4]);
rowFormattedMatches.add(matchesArray[5]);
formattedTempMatches.add(rowFormattedMatches);

【讨论】:

  • 谢谢,这是最有意义的。不知道为什么我没有想到这个。
猜你喜欢
  • 1970-01-01
  • 2012-12-26
  • 2022-01-02
  • 1970-01-01
  • 2011-05-04
  • 1970-01-01
  • 2015-11-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多