Explain Codes LogoExplain Codes Logo

Cast Int to enum in Java

java
enums
performance
error-handling
Anton ShumikhinbyAnton Shumikhin·Aug 17, 2024
TLDR

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.

public enum Color { RED, GREEN, BLUE; public static Color fromInt(int index) { Color[] colors = Color.values(); if(index < 0 || index >= colors.length) { throw new IllegalArgumentException("Invalid index: " + index); } return colors[index]; } } // Usage Color color = Color.fromInt(2); // Returns BLUE, feeling cool yet?

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.

public enum Color { RED(0), GREEN(1), BLUE(2); // Using distinct IDs for enum elements private final int id; Color(int id) { this.id = id; } public int getId() { return id; } public static Color fromId(int id) { for(Color color : Color.values()) { if(color.getId() == id) { return color; } } throw new IllegalArgumentException("No color with id: " + id); // Waving red flag } }

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'.

public enum Color { RED(0), GREEN(1), BLUE(2); private int id; private static final Map<Integer, Color> map = new HashMap<>(); static { for (Color color : Color.values()) { map.put(color.id, color); // Speedy access for later } } Color(int id) { this.id = id; } public static Color fromId(int id) { Color result = map.get(id); if (result == null) { throw new IllegalArgumentException("Invalid Color id: " + id); // No color blind allowed } return result; } }

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.

public static Color fromId(int id) throws IllegalArgumentException { // Error handling for unexpected entries if (!map.containsKey(id)) { throw new IllegalArgumentException("Invalid Color id: " + id); // Denied entry at the door } return map.get(id); }

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().

public static Color fromIdSwitch(int id) { switch (id) { case 0: return RED; case 1: return GREEN; case 2: return BLUE; default: throw new IllegalArgumentException("Invalid Color id: " + id); // Switching went wrong } }

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.