Java – Best way to create enum of strings

enumsjava

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?

Best Answer

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();