Lab 14: Advanced Enums

Objective

Master Java enums beyond simple constants: fields and methods, abstract methods per constant (state machine), EnumSet for efficient enum collections, EnumMap for enum-keyed maps, and pattern-matching switch for exhaustive enum dispatch.

Background

Java enums are full classes — each constant is a singleton instance. They can have fields, constructors, and methods. When combined with abstract methods, each constant can have its own behaviour: a compact and type-safe state machine. EnumSet and EnumMap use bit vectors and arrays internally — they're significantly faster than HashSet<E> and HashMap<E,V> for enum keys.

Time

25 minutes

Prerequisites

  • Lab 13 (Interfaces Advanced)

Tools

  • Docker: zchencow/innozverse-java:latest


Lab Instructions

Steps 1–8: Enum fields/methods, abstract methods (state machine), EnumSet, EnumMap, valueOf/ordinal, switch expression, Capstone

💡 EnumSet uses a long bitmask internally — membership testing and iteration are O(1) bit operations, not hash lookups. For enums with ≤64 constants, EnumSet is always faster than HashSet<OrderStatus>. Similarly, EnumMap uses an array indexed by ordinal(), making lookups array-access speed. Always prefer these specialised collections when your key/element type is an enum.

📸 Verified Output:


Summary

Feature
Notes

Enum with fields

Constructor sets fields; they're final

Enum with abstract method

Each constant must override it

EnumSet.of(...)

Bit-vector backed, very fast

EnumSet.complementOf(set)

All constants NOT in set

EnumMap<K,V>

Array-backed, ordinal-indexed

Enum.valueOf(name)

String → constant (throws on unknown)

Pattern switch

Exhaustive — no default needed

Further Reading

Last updated