I have an enum and I have an integer value associated to each. One of my function accepts that enum. In the function body, I want to fetch the associated int value. How I am doing it right now is it to create a map (with enum as key, and integer code as value) in the static block and use this map to get code corresponding to an enum. Is this the right way of doing it ? Or is there any better established way to achieve the same ?
public enum TAXSLAB {
SLAB_A(1),
SLAB_B(2),
SLAB_C(5);
private static final Map<TAXSLAB, Integer> lookup = new HashMap<TAXSLAB, Integer>();
static {
for(TAXSLAB w : EnumSet.allOf(TAXSLAB.class)) {
lookup.put(w, w.getCode());
}
}
private int code;
private TAXSLAB(int code) {
this.code = code;
}
public int getCode() {
return code;
}
public static int getCode(TAXSLAB tSlab) {
return lookup.get(tSlab);
}
}
Here is the related SO post. But here answer is suggesting to create the map with int value as key as enum as value. So this can not be used to fetch numeric value using enum without iterating through the map