Convert from enum ordinal to enum type
Need to convert an ordinal to an enum? Use the values() method:
Remember to check bounds to prevent ArrayIndexOutOfBoundsException
, unless you like wild indices running around!
Making it safe and speedy
Safeguard against unruly indices
Keep your ordinal indices well-behaved, always check if they are within bounds:
Cache values, bask in speed
Calling values()
often can be as tiresome as listening to a broken record. Make it once and store it using static field! You’re not just smart, you’re code-smart!
For the constant and judicious coder
Changing enums, constant headaches
You know how they say, "The only constant thing is change?" Not so fun when your data relies on the ordinal and the enum order changes. Use name() instead.
By doing so, you keep your enum robust, even if the order changes. Your data will still know their way home.
Converting like a pro
For easy reading and code cleanliness, put your conversion logic into a method or constructor:
Lookup tables, like a dictionary but faster
For those hungry for performance, consider using a HashMap. Who needs to line up when you can get it right away?
Was this article helpful?