I have an enum Type
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;
}
}
I get the values from the enum through the following code
Type[] type = Type.values();
for (int i = 0; i < type.length; i++) {
System.out.println(type[i].getValue());
}
This code runs on a server. For few days it runs fine and the output of this code is as follows :
abc1
abc2
abc3
abc4
abc5
But after few days the output changes to
abc1
abc2
abc1
abc4
abc5
If I print the description then they are always correct.
I am not able to figure out why Type.getValue() is returning value of enum Value A for enum Value C.
Your enum is mutable; something is calling setValue()
.
You should make your enum immutable - it makes good sense to do this. Make it immutable by making the fields final and ditching the setters:
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;
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.