Wednesday 29 June 2016

java - 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.


Answer



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


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...