【问题标题】:Java ArrayList independent copyJava ArrayList 独立拷贝
【发布时间】:2021-11-19 06:50:45
【问题描述】:
我使用下面的方法制作了一个列表的副本,你可以看到输出,它们是独立的。我是不是搞错了什么?还是他们真的独立?因为我在互联网上做了一些研究,它告诉我这个方法应该通过引用传递(哪个列表'a'和'copy'应该是依赖的)。
public static void main(String[] args) {
ArrayList<String> a = new ArrayList<>(Arrays.asList("X", "X"));
ArrayList<String> copy = new ArrayList<>(a);
copy.set(0, "B");
copy.remove(copy.size()-1);
System.out.println(a);
System.out.println(copy);
}
输出:
[X, X]
[B]
【问题讨论】:
标签:
java
arraylist
pass-by-reference
pass-by-value
【解决方案2】:
是的,这个方法应该通过引用传递(列表'a'和'copy'应该是依赖的)。但这两个操作并不能证明这一点。
copy.set(0, "B");
copy.remove(copy.size()-1);
看看下面的代码是否能帮助你理解:
public static void main(String[] args) {
Process process = new Process(1);
Process process2 = new Process(2);
ArrayList<Process> a = new ArrayList<>(Arrays.asList(process, process2));
ArrayList<Process> copy = new ArrayList<>(a);
copy.get(0).id = 10;
// This proves that both ArrayLists maintain the same Process object at this point
// output:
// [Id:10, Id:2]
// [Id:10, Id:2]
System.out.println(a);
System.out.println(copy);
// copy.remove(copy.size() - 1) or copy.set(0, process3) doesn't affect another ArrayList
Process process3 = new Process(3);
process3.id = 100;
copy.set(0, process3);
copy.remove(copy.size() - 1);
// output:
// [Id:10, Id:2]
// [Id:100]
System.out.println(a);
System.out.println(copy);
}
static class Process {
public int id;
public Process(int id) {
this.id = id;
}
@Override
public String toString() {
return "Id:" + id;
}
}