Java enum
types are powerful constructs used to define collections of constants with meaningful names. Each enum constant has an ordinal, which represents its position in the declaration (starting from 0). In some scenarios—such as deserializing data or interpreting numeric codes—you may need to convert an ordinal back to its corresponding enum constant.
In this article, we’ll walk you through how to set an enum value based on its ordinal in Java, explore practical use cases, and discuss potential pitfalls with this approach. Whether you’re a Java beginner or an experienced developer, understanding how to use enum ordinals effectively can improve the robustness of your code.
🧠 What Is an Enum Ordinal in Java?
Every enum constant in Java has a built-in ordinal value:
public enum Color {
RED, GREEN, BLUE
}
Color.RED.ordinal()
→ 0Color.GREEN.ordinal()
→ 1Color.BLUE.ordinal()
→ 2
Java assigns these ordinal values automatically based on the order in which enum constants are declared.
✅ How to Set an Enum Value by Ordinal
To get the enum value from an ordinal, use the values()
method, which returns an array of all enum constants in the declared order:
Example Code
public class EnumFromOrdinalExample {
public enum Color {
RED, GREEN, BLUE
}
public static Color getColorByOrdinal(int ordinal) {
Color[] values = Color.values();
if (ordinal >= 0 && ordinal < values.length) {
return values[ordinal];
} else {
throw new IllegalArgumentException("Invalid ordinal: " + ordinal);
}
}
public static void main(String[] args) {
int ordinalInput = 1; // Assume this value comes from a database or file
Color selectedColor = getColorByOrdinal(ordinalInput);
System.out.println("Selected color: " + selectedColor);
}
}
Output
Selected color: GREEN
🔥 Real-Life Use Cases
Setting enum values by ordinal may be useful in:
- Database Deserialization: When enums are stored as integers in the database.
- Communication Protocols: When enums are transmitted as numeric codes for compactness.
- Data Import/Export: Mapping numeric columns to enums when importing CSV or Excel files.
⚠️ Important Caveats
While enum.ordinal()
is convenient, it comes with significant downsides:
1. Fragile to Reordering
Changing the order of enum constants will change their ordinals, potentially breaking persisted data.
// Original
enum Status { NEW, IN_PROGRESS, DONE }
// Reordered
enum Status { DONE, IN_PROGRESS, NEW } // Ordinals changed!
2. Not Self-Descriptive
Using ordinal values in storage lacks readability and requires extra conversion logic.
🛡️ Best Practices
If you need to persist enums or transmit them reliably:
- Prefer
name()
or custom codes overordinal()
. - Use a field inside the enum to represent a stable value.
Example with Custom Code
public enum Status {
NEW(0), IN_PROGRESS(1), DONE(2);
private final int code;
Status(int code) {
this.code = code;
}
public int getCode() {
return code;
}
public static Status fromCode(int code) {
for (Status status : values()) {
if (status.getCode() == code) return status;
}
throw new IllegalArgumentException("Invalid code: " + code);
}
}
🚀 Conclusion
Java enum ordinals offer a quick way to reference constants by position, but they should be used with caution. When you set enum values by ordinal, make sure to validate the input and understand the implications of changing enum declaration order.
For stable and maintainable code, consider using enum fields or names instead of relying solely on ordinals. However, when performance and compactness are priorities—like in low-level communication protocols—ordinal mapping remains a viable solution.