Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert from enum ordinal to enum type

Tags:

java

enums

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.

like image 952
Lennie Avatar asked Mar 04 '09 09:03

Lennie


People also ask

How do you find the ordinal value of an enum?

The java. lang. Enum. ordinal() method returns the ordinal of this enumeration constant (its position in its enum declaration, where the initial constant is assigned an ordinal of zero).

What is ordinal in enum?

ordinal() tells about the ordinal number(it is the position in its enum declaration, where the initial constant is assigned an ordinal of zero) for the particular enum.

Can you typecast an enum?

Yes. In C enum types are just int s under the covers. Typecast them to whatever you want. enums are not always ints in C.

How do I convert string to enum?

Use the Enum. IsDefined() method to check if a given string name or integer value is defined in a specified enumeration. Thus, the conversion of String to Enum can be implemented using the Enum. Parse ( ) and Enum.


1 Answers

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

like image 96
Joachim Sauer Avatar answered Sep 20 '22 06:09

Joachim Sauer