Convert from enum ordinal to enum type

Lennie picture Lennie · Mar 4, 2009 · Viewed 161.4k times · Source

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.

Answer

Joachim Sauer picture Joachim Sauer · Mar 4, 2009

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