繁体   English   中英

名单 <List<Integer> &gt; ArrayList初始化不适用于新的运算符Java

[英]List<List<Integer>> ArrayList initialization does not work with new operator Java

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

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
}

这并不奇怪,因为您只需要迭代一个列表。 如果添加第二个列表,您将看到第二个数字。

int[] x = new int[]{1,2,3,4,5}; 

    List<List<Integer>> result = new ArrayList<>();
    result.add(new ArrayList());
result.add(new ArrayList());
    List<List<Integer>> temp = new ArrayList<>(result);
    for (Integer xx: x) {
        result.add(new ArrayList(xx));
    }
    System.out.println(result.toString());

如果您尝试使用此代码,它将显示以下内容:

[[1],[2]]

temp = new ArrayList<>(result)只做的浅表副本result ,即,它复制“外”列表中,而不是它的元件。

temp.get(0) == result.get(0) -我不是equals -它们是完全相同的实例。

这样,添加到temp.get(0)内容也将出现在result.get(0)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM