Jam Jam - 7 months ago 25
Java Question

How to get enum's numeric value?

Suppose you have

public enum Week {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}


How can one get
int
representing that Sunday is 0, Wednesday is 3 etc?

Answer
Week week = Week.SUNDAY;

int i = week.ordinal();

Be careful though, that this value will change if you alter the order of enum constants in the declaration. One way of getting around this is to self-assign an int value to all your enum constants like this:

public enum Week 
{
     SUNDAY(0),
     MONDAY(1)

     private static final Map<Integer,Week> lookup 
          = new HashMap<Integer,Week>();

     static {
          for(Week w : EnumSet.allOf(Week.class))
               lookup.put(w.getCode(), w);
     }

     private int code;

     private Week(int code) {
          this.code = code;
     }

     public int getCode() { return code; }

     public static Week get(int code) { 
          return lookup.get(code); 
     }
}