366

I've the enum type ReportTypeEnum that get passed between methods in all my classes but I then need to pass this on the URL so I use the ordinal method to get the int value. After I get it in my other JSP page, I need to convert it to back to an ReportTypeEnum so that I can continue passing it.

How can I convert ordinal to the ReportTypeEnum?

Using Java 6 SE.

1
  • 1
    There is no Java 6 EE, until now (AFAIK). There is Java SE 6, and Java EE 5.
    – Hosam Aly
    Mar 4, 2009 at 9:39

15 Answers 15

730

To convert an ordinal into its enum representation 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

3
  • 1
    I implemented this solution and it is not working for me. It returns out the ordinal value is not guaranteed to match the order in which the enumerated types are added. I don't know that is what this answer is advocating, but I wanted to warn people nonetheless
    – IcedDante
    Jul 14, 2015 at 0:06
  • @IcesDante: the ordinal is certainly guaranteed to correspond to the order of the Enumeration values in the source. If you observe a different behaviour, then something else must be wrong. My answer above is however suboptimal for all the reasons laid out in the other answers. Jul 14, 2015 at 8:35
  • @JoachimSauer Maybe IcedDante means the ordinal may not match if it was produced and saved by an earlier version of the source, in which the enum values were in a different order.
    – LarsH
    Jun 18, 2020 at 22:24
145

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?

12
  • 34
    What if you change the name of the enum (but keep the ordering)? Nov 11, 2009 at 15:06
  • 8
    @Arne - I think this is much less likely than some inexperienced person coming along and adding a value at either the start or its correct alphabetical/logical position. (By logical I mean for example TimeUnit values have a logical position) Nov 11, 2009 at 15:35
  • 8
    I certainly prefer to force the enums order rather than the name of my enum...this is why I prefer to store the ordinal rather than the name of the enum in the database. Furthermore, it's better to use int manipulation rather than String...
    – user660940
    Mar 15, 2011 at 16:06
  • 11
    I agree. In a public API, changing the name of an Enum would break backward compatibility but changing the order would not. For that reason, it makes more sense to use the name as your "key"
    – Noel
    Oct 11, 2011 at 21:31
  • 4
    Storing the ordinal makes it easier to translate your ideas to other languages. What if you need to write some component in C?
    – QED
    Mar 25, 2015 at 16:38
115

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.

5
  • 4
    +1 this is by far the best solution IMHO because one can pass ordinals around especially in android.os.Message.
    – likejudo
    Jun 22, 2017 at 17:14
  • 16
    This is very worrying because arrays are mutable. Even though values[] is final, it doesn't prevent Suit.values[0] = Suit.Diamonds; somewhere in your code. Ideally that will never happen, but the overall principle of don't expose mutable fields still holds. For this approach, consider using Collections.unmodifiableList or the like instead.
    – Mshnik
    Oct 13, 2017 at 17:55
  • 1
    How about - private static final Suit values[] = values(); public static Suit[] getValues() { return values; }
    – Pratyush
    Jul 17, 2018 at 12:41
  • 6
    @Pratyush that would make the array variable immutable, but not its contents. I could still do getValues()[0]=somethingElse;
    – Calabacin
    Dec 19, 2018 at 14:35
  • 1
    Agree, thus the point is not expose the Suit values[] directly or indirectly (how was mentioned through getValues()), I work around with a public method where the ordinal value must be sent how an argument and return the Suit representation from Suit values[]. The point here (question's tile from the beginning) was create an enum type from an enum ordinal Jul 23, 2019 at 17:57
19

I agree with most people that using ordinal is probably a bad idea. I usually solve this problem by giving the enum a private constructor that can take for example a DB value then create a static fromDbValue function similar to the one in Jan's answer.

public enum ReportTypeEnum {
    R1(1),
    R2(2),
    R3(3),
    R4(4),
    R5(5),
    R6(6),
    R7(7),
    R8(8);

    private static Logger log = LoggerFactory.getLogger(ReportEnumType.class);  
    private static Map<Integer, ReportTypeEnum> lookup;
    private Integer dbValue;

    private ReportTypeEnum(Integer dbValue) {
        this.dbValue = dbValue;
    }


    static {
        try {
            ReportTypeEnum[] vals = ReportTypeEnum.values();
            lookup = new HashMap<Integer, ReportTypeEnum>(vals.length);

            for (ReportTypeEnum  rpt: vals)
                lookup.put(rpt.getDbValue(), rpt);
         }
         catch (Exception e) {
             // Careful, if any exception is thrown out of a static block, the class
             // won't be initialized
             log.error("Unexpected exception initializing " + ReportTypeEnum.class, e);
         }
    }

    public static ReportTypeEnum fromDbValue(Integer dbValue) {
        return lookup.get(dbValue);
    }

    public Integer getDbValue() {
        return this.dbValue;
    }

}

Now you can change the order without changing the lookup and vice versa.

2
  • THIS is the right answer. I'm surprised it got so few points compared to other more direct but potentially invalid answers (due to code changes in the future).
    – Calabacin
    Dec 19, 2018 at 14:27
  • d= (◕‿↼ ) Only solution for flags where the integer can be anything (and is not ordered) like 0xDEAD for example.
    – Top-Master
    Nov 15, 2020 at 7:53
8

You could use a static lookup table:

public enum Suit {
  spades, hearts, diamonds, clubs;

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

  static {
    int ordinal = 0;
    for (Suit suit : EnumSet.allOf(Suit.class)) {
      lookup.put(ordinal, suit);
      ordinal+= 1;
    }
  }

  public Suit fromOrdinal(int ordinal) {
    return lookup.get(ordinal);
  }
}
6
  • 3
    See also Enums.
    – trashgod
    Jun 24, 2011 at 16:13
  • 13
    Wow! Just wow! This is neat, of course, but... you know - the C programmer inside me screams in pain seeing that you allocate a full-blown HashMap and perform lookups inside it all of it JUST to essentially manage 4 constants: spades, hearts, diamonds and clubs! A C programmer would allocate 1 byte for each: 'const char CLUBS=0;' etc... Yes,a HashMap lookup is O(1), but the memory and CPU overhead of a HashMap, in this case make it many orders of magnitude slower and resource hungry than calling .values() directly! No wonder Java is such a memory hog if people write like this...
    – Leszek
    Feb 27, 2015 at 14:15
  • 3
    Not every program requires the performance of a triple A game. In many cases trading memory and CPU for type safety, readability, maintainability, cross platform support, garbage collection, etc... is justifiable. Higher level languages exist for a reason.
    – Jan
    Sep 2, 2015 at 14:53
  • 4
    But if your key range is always 0...(n-1), then an array is less code and more readable as well; the performance boost is just a bonus. private static final Suit[] VALUES = values(); and public Suit fromOrdinal(int ordinal) { return VALUES[ordinal]; }. Extra advantage: crashes immediately on invalid ordinals, rather than silently returning null. (Not always an advantage. But often.)
    – Thomas
    Aug 8, 2016 at 8:05
  • Sorry, but no. Using a HashMap here is ludicrous. Use an array. Mar 14, 2022 at 17:01
5

This is what I use. I make no pretense that it's far less "efficient" than the simpler solutions above. What it does do is provide a much clearer exception message than "ArrayIndexOutOfBounds" when an invalid ordinal value is used in the solution above.

It utilizes the fact that EnumSet javadoc specifies the iterator returns elements in their natural order. There's an assert if that's not correct.

The JUnit4 Test demonstrates how it's used.

 /**
 * convert ordinal to Enum
 * @param clzz may not be null
 * @param ordinal
 * @return e with e.ordinal( ) == ordinal
 * @throws IllegalArgumentException if ordinal out of range
 */
public static <E extends Enum<E> > E lookupEnum(Class<E> clzz, int ordinal) {
    EnumSet<E> set = EnumSet.allOf(clzz);
    if (ordinal < set.size()) {
        Iterator<E> iter = set.iterator();
        for (int i = 0; i < ordinal; i++) {
            iter.next();
        }
        E rval = iter.next();
        assert(rval.ordinal() == ordinal);
        return rval;
    }
    throw new IllegalArgumentException("Invalid value " + ordinal + " for " + clzz.getName( ) + ", must be < " + set.size());
}

@Test
public void lookupTest( ) {
    java.util.concurrent.TimeUnit tu = lookupEnum(TimeUnit.class, 3);
    System.out.println(tu);
}
4

Safety first (with Kotlin):

// Default to null
EnumName.values().getOrNull(ordinal)

// Default to a value
EnumName.values().getOrElse(ordinal) { EnumName.MyValue }
1

This is what I do on Android with Proguard:

public enum SomeStatus {
    UNINITIALIZED, STATUS_1, RESERVED_1, STATUS_2, RESERVED_2, STATUS_3;//do not change order

    private static SomeStatus[] values = null;
    public static SomeStatus fromInteger(int i) {
        if(SomeStatus.values == null) {
            SomeStatus.values = SomeStatus.values();
        }
        if (i < 0) return SomeStatus.values[0];
        if (i >= SomeStatus.values.length) return SomeStatus.values[0];
        return SomeStatus.values[i];
    }
}

it's short and I don't need to worry about having an exception in Proguard

1

You can define a simple method like:

public enum Alphabet{
    A,B,C,D;

    public static Alphabet get(int index){
        return Alphabet.values()[index];
    }
}

And use it like:

System.out.println(Alphabet.get(2));
0
public enum Suit implements java.io.Serializable, Comparable<Suit>{
  spades, hearts, diamonds, clubs;
  private static final Suit [] lookup  = Suit.values();
  public Suit fromOrdinal(int ordinal) {
    if(ordinal< 1 || ordinal> 3) return null;
    return lookup[value-1];
  }
}

the test class

public class MainTest {
    public static void main(String[] args) {
        Suit d3 = Suit.diamonds;
        Suit d3Test = Suit.fromOrdinal(2);
        if(d3.equals(d3Test)){
            System.out.println("Susses");
        }else System.out.println("Fails");
    }
}

I appreciate that you share with us if you have a more efficient code, My enum is huge and constantly called thousands of times.

1
  • I think you meant "if(ordinal< 1 || ordinal> 4) return null;"
    – geowar
    Apr 16, 2020 at 19:38
0

So one way is to doExampleEnum valueOfOrdinal = ExampleEnum.values()[ordinal]; which works and its easy, however, as mentioned before, ExampleEnum.values() returns a new cloned array for every call. That can be unnecessarily expensive. We can solve that by caching the array like so ExampleEnum[] values = values(). It is also "dangerous" to allow our cached array to be modified. Someone could write ExampleEnum.values[0] = ExampleEnum.type2; So I would make it private with an accessor method that does not do extra copying.

private enum ExampleEnum{
    type0, type1, type2, type3;
    private static final ExampleEnum[] values = values();
    public static ExampleEnum value(int ord) {
        return values[ord];
    }
}

You would use ExampleEnum.value(ordinal) to get the enum value associated with ordinal

0

There is an Easy and Bad way and there is a fairly easy and right way.

First, the easy and bad (those are usually very popular). Enum class method returns an array of all available instances via the values() method and you can access the enum object via array index.

RenderingMode mode = RenderingMode.values()[index];

//Enum Class somewhere else
public enum RenderingMode
{
    PLAYING,
    PREVIEW,
    VIEW_SOLUTION;    
    
}
    

//RenderingMode.values()[0] will return RenderingMode.PLAYING
//RenderingMode.values()[1] will return RenderingMode.PREVIEW
//Why this is bad? Because it is linked to order of declaration.

//If you later changed the order here, it will impact all your existing logic around this.
public enum RenderingMode
    {
        
        PREVIEW,
        VIEW_SOLUTION,
        PLAYING;    
        
    }
 //Now
//RenderingMode.values()[0] will return RenderingMode.PREVIEW
//RenderingMode.values()[1] will return RenderingMode.VIEW_SOLUTION

Here is the right way to do it. Create a static method fromInt in your enum class.

public enum RenderingMode
{
    PLAYING,
    PREVIEW,
    VIEW_SOLUTION;

    public static RenderingModefromInt(int index)
    {
       //this is independent of order of declaration
        switch (index)
        {
            case 0: return PLAYING;
            case 1: return PREVIEW;
            case 2: return VIEW_SOLUTION;
        }
        //Consider throwing Exception here

        return null;
    }
}
0
public enum Status {
    STATUS_1, STATUS_2, STATUS_3, STATUS_4;

    public static Status getStatusByOrdinal(int ordinal) {
        for (Status status : values()) {
            if (status.ordinal() == ordinal) {
                return status;
            }
        }
        return STATUS_1;
    }
}
0

In this way you can not depend on compile-time generics resolution(so having an enum class instance you can create whenever enum you want, even those types created with Class.forMame)

public Object getInstance(Class enumClazz, int ordinal) throws Exception {
    Object[] allEnums = enumClazz.getDeclaredMethod("values", Object[].class).invoke(null, null);
    return allEnums[ordinal];
}
-1

Every enum has name(), which gives a string with the name of enum member.

Given enum Suit{Heart, Spade, Club, Diamond}, Suit.Heart.name() will give Heart.

Every enum has a valueOf() method, which takes an enum type and a string, to perform the reverse operation:

Enum.valueOf(Suit.class, "Heart") returns Suit.Heart.

Why anyone would use ordinals is beyond me. It may be nanoseconds faster, but it is not safe, if the enum members change, as another developer may not be aware some code is relying on ordinal values (especially in the JSP page cited in the question, network and database overhead completely dominates the time, not using an integer over a string).

5
  • 2
    Because comparing integers is much faster than comparing strings? Aug 24, 2013 at 4:55
  • 2
    But ordinals will change if someone modifies the enum (Adds/reorder memvers). Sometimes it is about safety and not speed, especially on a JSP page where the network latency is at 1,000,000 times the difference between comparing an array of integers (a string) and a single integer. Aug 25, 2013 at 11:18
  • toString can be overridden, so it may not return the enum name. The method name( ) is what gives the enum name (it's final)
    – gerardw
    Feb 10, 2014 at 14:21
  • code comments and application versions are also a thing (maybe a file format is simpler and smaller this way) Jan 21, 2019 at 16:01
  • Not sure why this was downvoted when it's essentially recommending the same thing as in oxbow_lakes' answer. Definitely safer than using the ordinal.
    – user11566289
    Jul 17, 2019 at 2:06

Not the answer you're looking for? Browse other questions tagged or ask your own question.