Given the following java enum:
public enum AgeRange {
A18TO23 {
public String toString() {
return \"18 - 23\";
}
},
According to effective java (2nd ed) item 30, it can be (it is much faster than the loop)
public enum AgeRange {
A18TO23("18-23"),
A24TO29("24-29"),
A30TO35("30-35");
private final String value;
AgeRange(String value){
this.value = value;
}
@Override public String toString(){
return value;
}
private static final Map stringToEnum =
new HashMap();
static {
for (AgeRange r : values()) {
stringToEnum.put(r.toString(), r);
}
}
public static AgeRange getByValue(String value){
return stringToEnum.get(value);
}
}