我的问题非常基本,但我想 100% 了解所有内容。SO中的许多问题都参考了我的帖子,但我还没有找到令人满意的答案。
我们知道java中的枚举是引用类型。让我们考虑以下代码段:
public static class A {
public int i;
public A(int i) {
this.i = i;
}
}
public static class Test {
int i;
A a;
public Test(int i, A a){
this.i = i;
this.a = a;
}
public Test(Test oldTest){
this.i = oldTest.i;
this.a = oldTest.a;
}
}
public static void main(String[] args) {
Test t1 = new Test(10, new A(100));
System.out.println(t1.i + " " + t1.a.i);
Test t2 = new Test(t1);
t2.i = 200;
t2.a.i = 3983;
System.out.println(t2.i + " " + t2.a.i);
System.out.println(t1.i + " " + t1.a.i);
}
输出非常明显,因为 Test 的拷贝构造函数做了一个浅拷贝:
10 100
200 3983
10 3983
但是因为 java 中的枚举也是引用类型,所以我不明白一件事。让我们用 Enum 替换 A 类:
public static enum TestEnum {
ONE, TWO, THREE;
}
public static class Test {
int i;
TestEnum enumValue;
public Test(int i, TestEnum enumVar){
this.i = i;
this.enumValue = enumVar;
}
public Test(Test oldTest){
this.i = oldTest.i;
this.enumValue = oldTest.enumValue; // WHY IT IS OK ??
}
}
public static void main(String[] args) {
Test t1 = new Test(10, TestEnum.ONE);
System.out.println(t1.i + " " + t1.enumValue);
Test t2 = new Test(t1);
t2.i = 200;
t2.enumValue = TestEnum.THREE; // why t1.emunValue != t2.enumValue ??
System.out.println(t2.i + " " + t2.enumValue);
System.out.println(t1.i + " " + t1.enumValue);
}
我期待输出:
10 ONE
200 THREE
10 THREE <--- I thought that reference has been copied... not value
但我有:
10 ONE
200 THREE
10 ONE
问:为什么?我的想法哪里不对?