Reputation: 1339
I see that simple enums can be created by these ways
public enum MyEnum1 {
FOO,
BAR;
}
public enum MyEnum2 {
FOO("FOO"),
BAR("BAR");
private final String value;
private MyEnum2(String value) {
this.value = value;
}
public String value() {
return value;
}
}
In the first case I can use MyEnum1.FOO.name()
whereas in the second I can use MyEnum2.FOO.value()
to serve my purpose. I want to know what is the best approach when I just want the enums to represent some constant set of Strings.
What are the pros/cons of using the above enums? Which should be preferred in which scenarios? Is there any drawback of using the name()
method?
Upvotes: 0
Views: 95
Reputation: 61
First solution will work for you. Second solution if you want extra info added to the enum:
public enum MyEnum2 {
FOO("This is the first", 867),
BAR("This is the second", 885);
private final String description;
private final Integer weight;
private MyEnum2(String description, Integer weight) {
this.description = description;
this.weight = weight
}
public String getDescription() {
return description;
}
public Integer getWeight() {
return weight;
}
}
Upvotes: 1
Reputation: 401
I'd say that depends on the use case. I agree with Jeremy, that 1st approach looks better and is cleaner. However, if some other code depends on the enum name, than I'd use 2nd approach, since in the 1st one, refactoring the enum will break your app. But if you only want to print the name somewhere, then use the 1st one.
Upvotes: 0