Java 43: Enums with Fields, Methods & EnumMap/EnumSet
easy⏱ 5 mincoursejava
Enums carry state and behavior
Each constant calls a private constructor with its data: MERCURY(3.3e23, 2.4e6). Add final fields, a constructor, and accessor methods. Because every constant is a singleton, == is safe and fast for comparison (no .equals() needed), and they're naturally usable as switch labels.
enum Planet {
EARTH(5.976e24, 6.37e6),
MARS (6.42e23, 3.39e6);
private final double mass, radius;
Planet(double m, double r) { mass = m; radius = r; }
double gravity() { return 6.67e-11 * mass / (radius * radius); }
}
Constant-specific bodies
Declare an abstract method on the enum and override it per constant — each constant becomes its own subclass instance. This is a tidy strategy pattern: Operation.PLUS.apply(2, 3) dispatches to PLUS's body. No switch, no fall-through bugs, exhaustive by construction.
enum Op {
PLUS { int apply(int a, int b) { return a + b; } },
TIMES { int apply(int a, int b) { return a * b; } };
abstract int apply(int a, int b);
}
EnumSet & EnumMap
EnumSet is a Set implemented as a bit vector — EnumSet.of(MON, FRI) is a single long for ≤64 constants, making contains/add O(1) and tiny. EnumMap is a Map backed by an array indexed by ordinal() — faster and denser than HashMap for enum keys, with predictable (declaration) iteration order. Prefer both over the generic collections whenever the keys are enum constants.
Build a gravity enum + EnumMap
Model Planet constants with mass+radius and a gravity() method (G = 6.67e-11). Compute the weight of a 75kg human on each planet (mass * gravity). Then build an enumMap (a Map keyed by the planet name, iterated in declaration order) of planet -> weight, and an enumSet of the 'low-gravity' planets where gravity < Earth's. Print both.
Never persist ordinal()
ordinal() returns the declaration index — but it shifts the moment someone reorders or inserts a constant, silently corrupting stored data. Persist the name (name() / valueOf) or an explicit stable code field instead. ordinal() is fine for in-memory EnumMap/EnumSet internals, never for serialization.
Quiz: enum singleton & threads
Why is a single-constant enum the recommended Singleton in Java? The JVM guarantees each enum constant is instantiated exactly once, lazily and thread-safely, and it's serialization-proof (no reflection or clone can duplicate it). Joshua Bloch's Effective Java calls it the best singleton implementation.