Practical Use Cases: State Machines and Configuration
You'll learn: How to apply EnumSet and EnumMap to solve real-world problems like managing permissions, tracking state transitions, and organizing configuration.
Why Enums Excel at These Problems
Enums represent fixed sets of related values—exactly what you need for permissions (READ, WRITE, DELETE), states (IDLE, RUNNING, PAUSED), or configuration options. EnumSet and EnumMap make working with these scenarios fast and type-safe.
Permission Sets with EnumSet
Instead of storing permissions as strings or integers, use an EnumSet:
enum Permission {
READ, WRITE, DELETE, EXECUTE
}
EnumSet<Permission> adminPerms = EnumSet.allOf(Permission.class);
EnumSet<Permission> guestPerms = EnumSet.of(Permission.READ);
if (guestPerms.contains(Permission.WRITE)) {
// Won't execute
}
This approach is type-safe (no typos like "WRTE"), fast (bit operations), and readable.
State Machines with EnumMap
Track which states can transition to others using an EnumMap:
enum State {
IDLE, RUNNING, PAUSED, STOPPED
}
EnumMap<State, EnumSet<State>> transitions = new EnumMap<>(State.class);
transitions.put(State.IDLE, EnumSet.of(State.RUNNING));
transitions.put(State.RUNNING, EnumSet.of(State.PAUSED, State.STOPPED));
transitions.put(State.PAUSED, EnumSet.of(State.RUNNING, State.STOPPED));
State current = State.RUNNING;
if (transitions.get(current).contains(State.PAUSED)) {
current = State.PAUSED; // Valid transition
}
Configuration Management
Store settings indexed by enum keys:
enum ConfigKey {
MAX_CONNECTIONS, TIMEOUT_MS, RETRY_COUNT
}
EnumMap<ConfigKey, Integer> config = new EnumMap<>(ConfigKey.class);
config.put(ConfigKey.MAX_CONNECTIONS, 100);
config.put(ConfigKey.TIMEOUT_MS, 5000);
int timeout = config.get(ConfigKey.TIMEOUT_MS);
Key Takeaway: Use EnumSet for groups of enum values (permissions, active flags) and EnumMap for enum-keyed data (state transitions, configuration) to gain type safety, performance, and clarity in real-world scenarios.