Convert from enum ordinal to enum type

To convert an ordinal into its enum represantation you might want to do this:

ReportTypeEnum value = ReportTypeEnum.values()[ordinal];

Please notice the array bounds.

Note that every call to values() returns a newly cloned array which might impact performance in a negative way. You may want to cache the array if it's going to be called often.

Code example on how to cache values().


This answer was edited to include the feedback given inside the comments


If I'm going to be using values() a lot:

enum Suit {
   Hearts, Diamonds, Spades, Clubs;
   public static final Suit values[] = values();
}

Meanwhile wherever.java:

Suit suit = Suit.values[ordinal];

If you want the array to be private, be my guest:

private static final Suit values[] = values();
public static Suit get(int ordinal) { return values[ordinal]; }

...

Suit suit = Suit.get(ordinal);

Mind your array bounds.


This is almost certainly a bad idea. Certainly if the ordinal is de-facto persisted (e.g. because someone has bookmarked the URL) - it means that you must always preserve the enum ordering in future, which may not be obvious to code maintainers down the line.

Why not encode the enum using myEnumValue.name() (and decode via ReportTypeEnum.valueOf(s)) instead?

Tags:

Java

Enums