Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to create enum of strings?

Tags:

java

enums

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?

like image 467
Dori Avatar asked Oct 20 '10 13:10

Dori


People also ask

How do I create an enum string?

There are two ways to convert an Enum to String in Java, first by using the name() method of Enum which is an implicit method and available to all Enum, and second by using toString() method.

Can you have an enum of strings?

Create Enumeration of Strings With Extension Function in C#There is no built-in method of declaring an enumeration with string values. If we want to declare an enumeration with string constants, we can use the enum class and an extension function to achieve this goal.

How do I use string enums?

In summary, to make use of string-based enum types, we can reference them by using the name of the enum and their corresponding value, just as you would access the properties of an object. At runtime, string-based enums behave just like objects and can easily be passed to functions like regular objects.


1 Answers

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

like image 154
Buhake Sindi Avatar answered Sep 21 '22 05:09

Buhake Sindi