我在这个问题上苦苦挣扎了两天。这个问题来自我正在做的一些问题。基本上,当我使用

List<List<Integer>> temp = new ArrayList<>(result);


创建一个新的ArrayList结果副本,当我尝试在高级for循环中更改温度时,结果将更改。例如,

List<List<Integer>> result = new ArrayList<>();
result.add(new ArrayList<>());
List<List<Integer>> temp = new ArrayList<>(result);
int j = 0;
for (List<Integer> list: temp) {
    list.add(x[j]);
    j ++;
}


我对循环内的结果不做任何操作,但结果以[[1]]结尾,与temp相同。

为什么会这样呢?非常感谢。

更新:感谢大家回答我的问题。我知道浅表副本是原因。但是,我仍然遇到类似的问题。当我尝试在以下代码中更改温度时,将更新结果:

List<List<Integer>> result = new ArrayList<>();
result.add(new ArrayList<>());
List<List<Integer>> temp = new ArrayList<>();
for (List<Integer> list: result) {
    list.add(10000);
    temp.add(new ArrayList(list));
}


我不知道为什么结果和温度一样是[[10000]]。像temp.add(new ArrayList(list))这样的add方法有什么问题吗?

最佳答案

发生这种情况是因为List<List<Integer>> temp = new ArrayList<>(result);语句仅复制顶级列表。这将是一个新列表,其中包含对原始result中原始项目(也称为子列表)的引用。

您可以使用深层副本来解决此问题:

List<List<Integer>> temp = new ArrayList<>(); // empty list
for (List<Integer> sublist : result) {
    temp.add(new ArrayList<Integer>(result)); // copying a sublist and adding that
}

07-24 09:49
查看更多