Tech Per

05 Feb

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, String) lets you get an enum instance from its type and name, but there is no valueOf which lets you get it from the ordinal value. What you can do, is provide your own valueOf method in your enum type, like this:

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 :-(

2 Responses to “Java5: From Ordinal Value To Enum Instance”

  1. 1
    Johann Zacharee Says:

    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) {
    if (ordinal = values.length) return null;
    return values[ordinal];
    }

  2. 2
    polesen Says:

    @Johann: God dammit, that’s so simple I’m nearly ashamed I missed it :-) Thanks!

Leave a Reply

© 2009 Tech Per | Entries (RSS) and Comments (RSS)

GPS Reviews and news from GPS Gazettewordpress logo