Best way to create enum of strings?

Dori picture Dori · Oct 20, 2010 · Viewed 478.1k times · Source

What is the best way to have a enum type represent a set of strings?

I tried this:

enum Strings{
   STRING_ONE("ONE"), STRING_TWO("TWO")
}

How can I then use them as Strings?

Answer

Buhake Sindi picture Buhake Sindi · Oct 20, 2010

I don't know what you want to do, but this is how I actually translated your example code....

package test;

/**
 * @author The Elite Gentleman
 *
 */
public enum Strings {
    STRING_ONE("ONE"),
    STRING_TWO("TWO")
    ;

    private final String text;

    /**
     * @param text
     */
    Strings(final String text) {
        this.text = text;
    }

    /* (non-Javadoc)
     * @see java.lang.Enum#toString()
     */
    @Override
    public String toString() {
        return text;
    }
}

Alternatively, you can create a getter method for text.

You can now do Strings.STRING_ONE.toString();