java - 从数组列表添加元素到 List<List<String>>

标签 java arrays list arraylist

我想将数据副本添加到我的列表中,但当我使用 .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);

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

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

最佳答案

调用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);

关于java - 从数组列表添加元素到 List<List<String>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37613898/

相关文章:

javascript - 将 javascript 变量分配给 java 变量

java - 使用java运行风扇

c# - 如何在 C# 中对具有原始顺序的列表进行排名

java - 如何使用 GSON 只返回一个特定的空字段?

java - 从纪元以来的几天获取 java.util.Calendar

php - 使用多维数组 PHP 插入数据库

php - php explode 并强制数组键从1开始而不是0

ios - 动态使用多维数组作为 UIImage 数组

jquery - 如何添加无序列表元素符号

java - 如何在JSP中迭代Mapped对象的列表项列表?