Hello,
what is the best way to have a enum type represent a set of strings eg
enum Strings{
STRING_ONE("ONE"), STRING_TWO("TWO")
}
so i can use them as Strings?
Thanks
Hello,
what is the best way to have a enum type represent a set of strings eg
enum Strings{
STRING_ONE("ONE"), STRING_TWO("TWO")
}
so i can use them as Strings?
Thanks
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
.
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")
;
/**
* @param text
*/
private Strings(final String text) {
this.text = text;
}
private final String text;
/* (non-Javadoc)
* @see java.lang.Enum#toString()
*/
@Override
public String toString() {
// TODO Auto-generated method stub
return text;
}
}
Alternatively, you can create a getter method for text.
You can now do Strings.STRING_ONE.toString();
Either set the enum name to be the same as the string you want or, more generally,you can associate arbitrary attributes with your enum values:
enum Strings {
STRING_ONE("ONE"), STRING_TWO("TWO");
private String stringValue;
Strings(String s) { stringValue = s; }
public String toString() { return stringValue; }
// further methods, attributes, etc.
}
It's important to have the constants at the top, and the methods/attributes at the bottom.
Depending on what you mean by "use them as Strings", you might not want to use an enum here. In most cases, the solution proposed by The Elite Gentleman will allow you to use them through their toString-methods, e.g. in System.out.println(STRING_ONE)
or String s = "Hello "+STRING_TWO
, but when you really need Strings (e.g. STRING_ONE.toLowerCase()
), you might prefer defining them as constants:
public interface Strings{
public static final String STRING_ONE = "ONE";
public static final String STRING_TWO = "TWO";
}