gpt4 book ai didi

java - 我正在填充 ArrayList 类型的 ArrayList。插入完成两次,但结果仅反射(reflect)第二次更新。解释

转载 作者:行者123 更新时间:2023-12-05 01:28:44 25 4
gpt4 key购买 nike

       ArrayList<ArrayList<Integer>> list = new ArrayList<>();
int i=0;
ArrayList<Integer> l = new ArrayList<>();
l.add(1);
l.add(4);
list.add(i,l);
i++;

l.clear();
l.add(0);
l.add(4);
l.add(3);
l.add(2);
list.add(i,l);

现在我的列表有 2 个具有相同值的元素 {0,4,3,2} 。 {1,4} 会怎样?

最佳答案

事情是这样的。 list 包含对 l 的引用。因此,当您清除 l 时,您将清除添加到 list 的那个。但是引用仍然存在以接受新值。

ArrayList<ArrayList<Integer>> list = new ArrayList<>();
int i=0;
ArrayList<Integer> l = new ArrayList<>();
l.add(1);
l.add(4);
list.add(i,l);
i++;

l.clear(); // you just deleted all the contents of list `l` but not the list `l` itself.
l.add(0);
l.add(4);
l.add(3);
l.add(2); // now list `l` (the reference still in `list` contains 0,4,3,2
list.add(i,l); // and now list contains the same reference yet again so you get

System.out.println(list);

打印

[[0, 4, 3, 2], [0, 4, 3, 2]]

请注意,如果您这样做,list.get(0).set(1,99) 将影响两个列表,因为列表 中的每个列表 l >list 是对同一列表的引用。

[[0, 99, 3, 2], [0, 99, 3, 2]]

关于java - 我正在填充 ArrayList<Integer> 类型的 ArrayList。插入完成两次,但结果仅反射(reflect)第二次更新。解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68352367/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com