How to convert enum value to int?
You can convert an enum
to an int
in Java using the ordinal()
function, which returns a zero-based index of the enum constant.
Here's a simplistic example:
Warning: The ordinal()
method returns the declaration order. If you shuffle the enum's constants, their corresponding ordinal values change too, turning the whole system into a chaotic dancing session, and possibly breaking something.
Beyond the ordinal(): custom int for enums
Not all scenarios call for ordinal values — maybe you want custom integer values tied to your enum constants? This is how you could do that:
Here the .ordinal()
would create a Pandora's box, incorrectly mapping REDUCED
to 2
instead of 5
. We tackled it with getTaxValue()
that fetches the right integer.
Looking at enum-int conversion alternates
Scenario: computation needed
When calculation or logic are involved, a switch-case
can come handy.
Scenario: enums aren't fitting well
When an enum
is more of a square peg for a round hole, consider a static class
with public final fields. This follows C# enum's suit of explicitly linking each name to an integer.
Crossing the 'i's and dotting the 't's
The order of constancy
If your code leans heavily on ordinal()
, remember to chisel those enum orders in stone. or, at the very least, write them in bold letters for your future self or the next coders.
The growth of enums
For dynamic enums that might acquire more constants, it's better to tie them to explicit integers or to bind them with a custom getter method. This makes future expansion less chaotic and intentions more transparent.
Enum vs int
In Java, enums are an overhead compared to ints since they're essentially classes, but they shine in providing type safety, a clear context, and better code readability.
Was this article helpful?