为什么修改一个数组列表的副本后会更改它 [英] Why does one arraylist change when a copy of it is modified
问题描述
它可能很简单,但是仍然让我感到困惑!
Its probably a very simple one but its' still confusing me!
import java.util.ArrayList;
public class Sample {
ArrayList<Integer> i = new ArrayList<>();
ArrayList<Integer> j = new ArrayList<>();
/**
* @param args
*/
public static void main(String[] args) {
new Sample().go();
}
private void go() {
i.add(1);
i.add(2);
i.add(3);
j=i;
i.remove(0);
System.out.println(i + "asd" + j);
}
}
我尝试打印它:
[2, 3]asd[2, 3]
当我改变时,j为什么会改变?原始类型却不会发生!
Why does j change when i changes? Does not happen with primitives though!
推荐答案
语句 j = i;
将引用 j
分配为与相同的引用我
.现在, i
和 j
都引用相同的 ArrayList
对象.通过两个引用都可以轻松看到删除第0个索引.
The statement j=i;
assigns the reference j
to be the same reference as i
. Now both i
and j
refer to the same ArrayList
object. The removal of the 0th index is simply visible through both references.
如果您希望删除 i
中的一项不影响 j
中的列表,请创建列表的副本,而不是分配引用:
If you would like the removal of an item in i
not to affect the list from j
, then create a copy of the list, instead of assigning the references:
j = new ArrayList<Integer>(i);
(这是一个浅表副本,因此列表仍然引用相同的元素.)
(It's a shallow copy, so the lists still refer to the same elements.)
这篇关于为什么修改一个数组列表的副本后会更改它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!