Explain Codes LogoExplain Codes Logo

Convert from enum ordinal to enum type

java
enum
best-practices
performance
Anton ShumikhinbyAnton Shumikhin·Dec 17, 2024
TLDR

Need to convert an ordinal to an enum? Use the values() method:

enum Cryptocurrency { BITCOIN, ETHEREUM, DOGECOIN; } Cryptocurrency crypto = Cryptocurrency.values()[2]; // DOGECOIN

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:

if (ordinal >= 0 && ordinal < Cryptocurrency.values().length) { Cryptocurrency crypto = Cryptocurrency.values()[ordinal]; } else { // Sweetly tell the ordinal, "Sorry dear, you're out of line!" }

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!

enum Cryptocurrency { BITCOIN, ETHEREUM, DOGECOIN; private static final Cryptocurrency[] VALUES = values(); public static Cryptocurrency fromOrdinal(int ordinal) { if (ordinal >= 0 && ordinal < VALUES.length) { return VALUES[ordinal]; } throw new IllegalArgumentException("The ordinal went rogue. Invalid ordinal alert!"); } }

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.

String cryptoName = myCrypto.name(); // Now it's a name, not just a number Cryptocurrency myCrypto = Cryptocurrency.valueOf(cryptoName); // Bring that crypto home!

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:

enum MyEnum { /* ... */ public static MyEnum fromDbValue(int dbValue) { // Your logic to transform dbValue to MyEnum } private MyEnum(int value) { // Your constructor logic } }

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?

enum MyEnum { /* ... */ ; private static final Map<Integer, MyEnum> lookup = new HashMap<>(); static { for (MyEnum e: values()) { lookup.put(e.ordinal(), e); } } public static MyEnum fromOrdinal(int ordinal) { return lookup.get(ordinal); } }