This week's book giveaway is in the Java 8 forum.
We're giving away four copies of Java 8 in Action and have Raoul-Gabriel Urma, Mario Fusco, and Alan Mycroft on-line!
See this thread for details.
The moose likes Java in General and the fly likes Convert from enum ordinal/constant to enum type Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Convert from enum ordinal/constant to enum type" Watch "Convert from enum ordinal/constant to enum type" New topic
Author

Convert from enum ordinal/constant to enum type

will zhang
Ranch Hand

Joined: Sep 11, 2008
Posts: 46
I want to get enum type based on the code(an int)
Here's what I have using switch:



Is there any way I can use instead of switch?

I saw something here: http://stackoverflow.com/questions/609860/convert-from-enum-ordinal-to-enum-type
But I couldn't understand the second method, any hint?

Thanks
John de Michele
Rancher

Joined: Mar 09, 2009
Posts: 600
Will:

You could create a static Map with your codes as keys and your enums as values.

John.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19552
    
  16

Or loop over the array returned by values():
It's a bit of a choice which one to use, the loop or the Map. The Map is faster (O(1)) but requires extra memory to store it. The loop doesn't need the memory but needs to loop each time (O(n)).


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Convert from enum ordinal/constant to enum type
 
Similar Threads
generic question
Enumeration.
Map Problem
static methods and NULL
Sorting question