I have an enum with values like this (the example just shows a few of the values but you will catch on): _800, _830, _900, _24HOURS, CLOSED
These have a corresponding value, so I added to my enum, which you can do in Java, a value field and a getter and setter for the value, like this (for space sake I do not show the getter and setter but they are the standard ones):
enum Hours {
_800("08:00"),
_830("08:30"),
CLOSED("Closed"),
APPT("By Appt.")
// etc
;
Hours(String v) {
val = v;
}
String val;
}
I also want to be able to go the other direction, that is, if I have a value (e.g. "08:00") I want it to return the enum _800. So to the enum I added a map:
static Map<String,String> valToEnumMap = new HashMap();
then I added this to my constructor:
Hours(String v) {
val = v;
valToEnumMap.put(v, this);
}
and a new method:
Hours valToEnum(String v) {
return valToEnumMap(v);
}
but when I try running it I get an initialization error at the point where it tries to insert into the map. I have tried other things like
valToEnumMap.put(v, valueOf(name());
but the same error. I did find a workaround but it is very slow, so I wonder what I did wrong? Here is the workaround I used which is slow:
public static OfficeHoursTimes valToEnum(String val) {
for (OfficeHoursTimes o : OfficeHoursTimes.values()) {
if (o.getVal().equals(val)) {
return o;
}
}
return null;
}
But there has to be a better way