测试代码后(见下文),我发现我不了解一些基础知识。
A 类。
class A {
private String s;
private int[] array;
private B b;
public A(String s, int[] array, B b) {
this.s = s;
this.array = array;
this.b = b;
}
}
B 级。
class B {
public int t;
public B(int t) {
this.t = t;
}
}
我认为我在 A a = new A(s, array, b);
之后所做的任何更改都会影响 a
。 a
的所有字段和变量s
、array
、b
不都指向同一个对象吗?
String s = "Lorem";
int array[] = new int[] {
10, 20, 30
};
B b = new B(12);
A a = new A(s, array, b);
s = "Dolor";
array = new int[] {
23
};
b = new B(777); // Initialized with a new value, a.b keeps the old one. Why?
System.out.println(a);
输出。
String Lorem
Array [10, 20, 30]
B 12
关于这个。
B b2 = new B(89);
B b3 = b2;
System.out.println(b3);
b2 = null;
System.out.println(b3); // b2 initialized with null, b3 keeps the old one. Why?
输出。
89
89
但是,如果我有两个列表,这表明它们都引用同一个对象。
ArrayList<String> first = new ArrayList<String>();
first.add("Ipsum");
ArrayList<String> second = new ArrayList<String>();
second = first;
first.add("The Earth");
System.out.println(second);
输出。
[Ipsum, The Earth]
最佳答案
区别在于赋值与修改。
赋值 (=
) 使变量指向其他内容,因此这不会更改基础数据。因此指向相同数据的任何其他变量都不会改变。
修改(除了 =
之外的几乎所有内容)不会更改变量指向的内容,它只会修改基础对象。因此,指向相同数据的任何其他变量都会发生变化。
例如:
b = new B(777);
是赋值,因此只有 b
被更改为指向其他内容。 a.b
不会改变。
b2 = null;
是赋值,因此只有 b2
被更改为指向其他内容。 b3
不会改变。
如果你说 b2.t = 5
,这将是修改(我们没有为 b2
分配新值,我们正在修改它更改其成员之一),因此 b3
也会更改。
我希望这能解释清楚。
关于Java复制理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16768133/