0

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

How to get enum's numeric value?

Community
  • 1
  • 1
Andy897
  • 6,915
  • 11
  • 51
  • 86

1 Answers1

3

You do not need the map to retrieve code from an enum object, because the call of TAXSLAB.getCode(s) produces the same value as s.getCode():

TAXSLAB s = ...
int c1 = TAXSLAB.getCode(s);
int c2 = s.getCode();
// c1 == c2 here

int code is a field of enum TAXSLAB object, so you can get it directly.

This works for values associated with an enum from within the enum. If you need to associate a value with an enum outside the enum, the most performant way of doing it is by using EnumMap class designed specifically for this purpose.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523