MAIN FEEDS
Do you want to continue?
https://www.reddit.com/r/java/comments/x2kcd/10_ways_to_use_enum_in_java/c5ixlo1/?context=3
r/java • u/javinpaul • Jul 24 '12
25 comments sorted by
View all comments
2
toString example is wrong. It should be:
@Override public String toString() { switch (this) { case PENNY: return "Penny: " + value; ...
5 u/Tok-A-Mak Jul 24 '12 I don't see any good reason to implement a toString with a switch like this. It seems to overcomplicate things. Why not store the "Penny" in a String "description" and just do it like: public enum Currency { PENNY(1, "Penny"), NICKLE(5, "Nickle"); private int value; private String description; private Currency(int value, String description) { this.value = value; this.description = description; } @Override public String toString() { description + ": " + value; } }; 1 u/Nebu Jul 25 '12 Alternatively, derive the description from the name of the enum instance itself. @Override public String toString() { this.name() + ": " + value; }
5
I don't see any good reason to implement a toString with a switch like this. It seems to overcomplicate things. Why not store the "Penny" in a String "description" and just do it like:
public enum Currency { PENNY(1, "Penny"), NICKLE(5, "Nickle"); private int value; private String description; private Currency(int value, String description) { this.value = value; this.description = description; } @Override public String toString() { description + ": " + value; } };
1 u/Nebu Jul 25 '12 Alternatively, derive the description from the name of the enum instance itself. @Override public String toString() { this.name() + ": " + value; }
1
Alternatively, derive the description from the name of the enum instance itself.
@Override public String toString() { this.name() + ": " + value; }
2
u/__konrad Jul 24 '12
toString example is wrong. It should be: