Best way to create enum of strings?
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
?
Solution 1:
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();
Solution 2:
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 one
this is two
Solution 3:
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
.