Best way to create enum of strings? Best way to create enum of strings? java java

Best way to create enum of strings?


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


Custom String Values for Enum

from http://javahowto.blogspot.com/2006/10/custom-string-values-for-enum.html

The default string value for java enum is its face value, or the element name. However, you can customize the string value by overriding toString() method. For example,

public enum MyType {  ONE {      public String toString() {          return "this is one";      }  },  TWO {      public String toString() {          return "this is two";      }  }}

Running the following test code will produce this:

public class EnumTest {  public static void main(String[] args) {      System.out.println(MyType.ONE);      System.out.println(MyType.TWO);  }}this is onethis is two


Use its name() method:

public class Main {    public static void main(String[] args) throws Exception {        System.out.println(Strings.ONE.name());    }}enum Strings {    ONE, TWO, THREE}

yields ONE.