gpt4 book ai didi

java - 枚举类型引用或原始类型(带有示例)- 浅/深复制

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:17:56 28 4
gpt4 key购买 nike

我的问题很基础,但我想 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 中的枚举也是引用类型我不明白一件事。让我们用枚举替换 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

问题:为什么?我的想法哪里不对?

最佳答案

这里的枚举没有什么特别之处。基本上,如果您使用字符串或任何 类型,您将看到完全相同的行为。

您的两个 Test 对象是完全独立的。当你写:

t2.enumValue = TestEnum.THREE;

您正在将第二个对象中的 enumValue 字段的值更改为对 TestEnum.THREE 引用的对象的引用。

两个 enumValue 字段(一个通过 t1,一个通过 t2)是完全独立的。更改一个字段不会更改另一个字段。

现在,如果改为让枚举可变(我强烈不鼓励这样做)并将代码更改为如下所示:

t2.enumValue.someMutableField = "a different value";

...那么通过t1.enumValue可见,因为它们都引用同一个对象。

区分更改 Test 实例中的字段和更改您碰巧通过 实例到达的对象中的字段非常重要>测试

再次声明,这真的与枚举无关。您可能会发现通过将 enumValue 字段更改为 String 字段并以这种方式进行试验,更容易理解这个想法。

关于java - 枚举类型引用或原始类型(带有示例)- 浅/深复制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16936100/

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