Java5: From Ordinal Value To Enum Instance
The enum type introduced in Java5 is quite powerful, but I miss a factory method to get an enum instance from its ordinal value. The existing factory method in Enum.valueOf(Class
public enum Weekday {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;
private static final Map<Integer, Weekday> ORDINAL_TO_ENUM_MAPPING = new HashMap<Integer,Weekday>(){{
for (Weekday weekday : Weekday.values()) {
put(weekday.ordinal(), weekday);
}
}};
public static Weekday valueOf(int ordinal) {
return ORDINAL_TO_ENUM_MAPPING.get(ordinal);
}
}
The above Weekday enum type has a statically initialized construct in the ORDINAL_TO_ENUM_MAPPING Map, which holds an ordinal value to enum mapping, for all the enums in the type. The implementation of the valueOf(int) method then becomes very easy, as it is simply a lookup in the Map. You can then say Weekday.valueOf(2), and get back a reference to Weekday.TUESDAY.
Sadly, you will have to redo this method in all enums you want it in ![]()


Why do you need a method?
You can just use Weekday.values[2] and get the same thing.
If you need range safety, create a method that checks the ordinal and then indexes into the values array. No need to build a map.
public static valueOf(int ordinal) {
February 6th, 2008 at 03:45if (ordinal = values.length) return null;
return values[ordinal];
}
@Johann: God dammit, that’s so simple I’m nearly ashamed I missed it
Thanks!
February 6th, 2008 at 09:06