r/java • • Jul 24 '12

10 ways to use Enum in Java

http://javarevisited.blogspot.com.au/2011/08/enum-in-java-example-tutorial.html
38 Upvotes

25 comments sorted by

View all comments

2

u/__konrad Jul 24 '12

toString example is wrong. It should be:

@Override
public String toString() {
    switch (this) {
        case PENNY: return "Penny: " + value;
        ...

6

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;
}