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
?
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.
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With