library
intermediateEnumSet & EnumMap
Use specialized, high-performance collections for enum keys/elements instead of HashSet/HashMap.
EnumSet and EnumMap are specialized collections for enum types, offering significantly better performance than their general-purpose counterparts.
EnumMap = a fixed-size mailbox row (one slot per apartment/enum). You go directly to slot 3 for enum ordinal 3. HashMap = a post office with hash lookups — much more overhead for a small, fixed set of keys.
Key Concepts
1
EnumSet<E extends Enum<E>>:
- Implemented as a bit vector: each enum constant is one bit
- All operations are O(1) (bitwise operations)
- Much faster and more memory-efficient than HashSet<E>
- No null elements allowed
- Ordered by enum declaration order
- Factory methods: EnumSet.of(), EnumSet.allOf(), EnumSet.noneOf(), EnumSet.range(), EnumSet.complementOf()
2
EnumMap<K extends Enum<K>, V>:
- Implemented as an array indexed by enum ordinal
- All operations are O(1) (array index)
- Much faster than HashMap<K, V> for enum keys
- Null values allowed, null keys not
- Ordered by enum declaration order
3
When enums have ≤ 64 constants, EnumSet uses a single long (RegularEnumSet). For > 64 constants, it uses a long[] (JumboEnumSet).
4
Common pattern: use EnumSet for flags/permissions instead of bitmasks. EnumSet.of(READ, WRITE) is more readable and type-safe than READ | WRITE.