gpt4 book ai didi

java - 枚举 getter 返回错误值

转载 作者:行者123 更新时间:2023-12-01 22:05:45 24 4
gpt4 key购买 nike

我有一个枚举类型

public enum Type {
A("abc1", "desc1"),
B("abc2", "desc2"),
C("abc3", "desc3"),
D("abc4", "desc4"),
E("abc5", "desc5");

private String value;
private String description;

private Type(String value, String description) {
this.value = value;
this.description = description;
}

public String getDescription() {
return description;
}

public void setDescription(String description) {
this.description = description;
}

public String getValue() {
return value;
}

public void setValue(String value) {
this.value = value;
}
}

我通过以下代码从枚举中获取值

Type[] type = Type.values();

for (int i = 0; i < type.length; i++) {
System.out.println(type[i].getValue());
}

此代码在服务器上运行。几天来它运行良好,代码的输出如下:

abc1
abc2
abc3
abc4
abc5

但是几天后输出变为

abc1
abc2
abc1
abc4
abc5

如果我打印描述,那么它们总是正确的。

我无法弄清楚为什么 Type.getValue() 为枚举值 C 返回枚举值 A 的值。

最佳答案

你的枚举是可变的;有东西正在调用 setValue()

您应该将枚举设为 immutable - 这样做很有意义。通过将字段设置为最终字段并放弃 setter 来使其不可变:

public enum Type {
A("abc1", "desc1"),
B("abc2", "desc2"),
C("abc3", "desc3"),
D("abc4", "desc4"),
E("abc5", "desc5");

private final String value;
private final String description;

private Type(String value, String description) {
this.value = value;
this.description = description;
}

public String getDescription() {
return description;
}

public String getValue() {
return value;
}
}

}

关于java - 枚举 getter 返回错误值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32843599/

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