Given a string i want to get the enum equivalent of it in constant time. I have a enum defined like the one shown in the question. Best way to create enum of strings?
Since Enum.valueOf
operates on the built-in name of the enum
(i.e. "STRING_ONE"
and "STRING_TWO"
) you would need to roll your own "registry" of name-to-enum, like this:
public enum Strings {
STRING_ONE("ONE"),
STRING_TWO("TWO")
;
private static final Map byName = new HashMap();
private final String text;
private Strings(final String text) {
this.text = text;
}
static {
for (Strings s : Strings.values()) {
byName.put(s.toString(), s);
}
}
@Override
public String toString() {
return text;
}
public static Strings forName(String name) {
return byName.get(name);
}
}
Demo.
Above, a map from string name to enum Strings
is used to do the translation. If the name is not there, null
would be returned from the Strings.forName
method.