OOP

30. Enums in Depth

Java enum is a full class โ€” enum constants can have fields, constructors, and methods; EnumSet and EnumMap provide highly efficient enum-keyed set/map implementations.

Java 21 (core language)

Explanation

Java enums are classes that extend java.lang.Enum. Each constant is a public static final instance of the enum class. Enums can have instance fields, constructors (always package-private or private), and abstract methods (where each constant provides its own implementation via an anonymous class body).

Built-in methods: name() returns the constant name as a string; ordinal() returns the 0-based declaration order (fragile โ€” don't use for persistence); values() returns all constants; valueOf(String) looks up by name.

EnumSet is a bit-vector-backed Set of enum values โ€” extremely fast and compact. EnumMap is an array-backed Map<EnumKey, V> โ€” faster than HashMap for enum keys. Prefer these over general HashSet/HashMap when the key is an enum.

Example

import java.util.EnumMap;
import java.util.EnumSet;
import java.util.Map;
import java.util.Set;

public class EnumsInDepth {
    enum Planet {
        MERCURY(3.303e+23, 2.4397e6),
        VENUS  (4.869e+24, 6.0518e6),
        EARTH  (5.976e+24, 6.37814e6),
        MARS   (6.421e+23, 3.3972e6);

        private final double mass;    // kg
        private final double radius;  // m
        static final double G = 6.67300E-11;

        Planet(double mass, double radius) {
            this.mass   = mass;
            this.radius = radius;
        }

        double surfaceGravity() { return G * mass / (radius * radius); }
        double surfaceWeight(double otherMass) { return otherMass * surfaceGravity(); }
    }

    enum Day {
        MON, TUE, WED, THU, FRI, SAT, SUN;
        public boolean isWeekend() { return this == SAT || this == SUN; }
    }

    public static void main(String[] args) {
        double earthWeight = 75.0; // kg
        double mass = earthWeight / Planet.EARTH.surfaceGravity();

        for (Planet p : Planet.values()) {
            System.out.printf("Weight on %-7s: %.2f N%n", p, p.surfaceWeight(mass));
        }

        // EnumSet: bit-vector backed, very fast
        Set<Day> weekdays = EnumSet.range(Day.MON, Day.FRI);
        Set<Day> weekend  = EnumSet.of(Day.SAT, Day.SUN);
        System.out.println("Weekdays: " + weekdays);
        System.out.println("Weekend:  " + weekend);
        System.out.println("Mon is weekend? " + Day.MON.isWeekend());

        // EnumMap: array-backed, faster than HashMap for enum keys
        Map<Day, String> schedule = new EnumMap<>(Day.class);
        schedule.put(Day.MON, "Team standup");
        schedule.put(Day.FRI, "Sprint review");
        schedule.forEach((day, event) -> System.out.println(day + ": " + event));
    }
}

Sources