Skip to content
Advertisement

Convert from enum ordinal to enum type

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.

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement