Cast Int to enum in Java
You can cast an int
to an enum
by accessing the ordinal position in the enum's array with EnumClass.values()[intValue]
. Just make sure the int is a valid ordinal to avoid headaches.
Enums with predefined IDs — a convenient option
This solution avoids frequent calling values()
method and makes your enumerations self-describing. Plus, it pairs enums with explicit integer IDs.
Boost up with static methods or collections
How about using a hash table for int
to enum
mapping? This could avoid calling values()
for each conversion and make it faster. For those with the 'need for speed'.
Making it watertight
A bunch of integers knocking on the door and some of them aren't on the guest list. Better to handle potential invalid inputs gracefully.
Casting int to enums — the do's and don'ts
Leveraging switch-case statements
Have a heavy load of values? Keep calm and try switch-case. It's faster than looping through values()
.
Watch for thread safety
If you're performing in a multi-threaded acrobatic, make sure your static operations are thread-safe. You never know who's watching from where!
Performance matters, mind the GC
Calling values()
creates a new array every time. It may look sophisticated but a real performance killer. Why? Because it leaves a lot of garbage for GC (Garbage Collector) to pick up. Avoid calling it repeatedly for smoother performance.
Was this article helpful?