Scrivio Interview library
ConceptFoundations6 min read · updated 12 November 2026

How are EnumSet and EnumMap implemented, and why are they faster than HashSet and HashMap with enum keys?

EnumSet is a bit vector: for enums with up to 64 constants, RegularEnumSet keeps one long where bit i means the constant with ordinal i is present, and for larger enums JumboEnumSet uses an array of longs. EnumMap keeps its values in a plain array indexed by ordinal. Because there is no hashing, no per-entry node objects and no boxing, contains, add and get are a few bit or array operations, and iteration follows declaration order. Neither is thread-safe, EnumMap rejects null keys and EnumSet rejects null elements.

Why this question is asked

Most developers know that EnumSet and EnumMap are recommended for enum keys, but fewer can say why. The answer is a neat example of how a strong guarantee, a fixed set of constants with stable ordinals, lets a data structure skip almost all of the work a general-purpose one does. Interviewers ask it to check our understanding of both enums and collection internals. In this answer, we will recap ordinals, see how EnumSet stores a set in bits, how EnumMap stores values in an array, compare the cost with HashSet and HashMap, and look at the rules around ordering, nulls and threads.

1A Quick Recap: Ordinals Make This Possible

Every enum constant has an ordinal, its zero-based position in the declaration. While a program runs, the set of constants is fixed and each ordinal is stable, and no new instance can ever appear. So an enum with five constants can be mapped perfectly onto the numbers 0 to 4, with no collisions and no unknown keys. A general HashSet must handle any object, compute hashes, and deal with collisions. An enum-specific set can simply use the ordinal as a position.

2How EnumSet Stores a Set in Bits

EnumSet is an abstract class with two hidden implementations. When we create one, for example with EnumSet.noneOf() or EnumSet.of(), it looks at how many constants the enum has. Up to 64, it creates a RegularEnumSet, which keeps one long field. Bit i of that long is 1 when the constant with ordinal i is in the set. For more than 64 constants, it creates a JumboEnumSet, which keeps a long[] with one long per 64 constants.

Java
enum Day { MON, TUE, WED, THU, FRI, SAT, SUN } // ordinals 0..6
EnumSet<Day> weekend = EnumSet.of(Day.SAT, Day.SUN);
// inside RegularEnumSet: elements = 0b1100000 (bits 5 and 6 set) = 96
weekend.contains(Day.SUN); // (96 & (1L << 6)) != 0 -> true
weekend.add(Day.FRI); // elements |= 1L << 4 -> 0b1110000 = 112
weekend.size(); // Long.bitCount(112) = 3
weekend.getClass().getSimpleName(); // RegularEnumSet
EnumSet<Day> weekend as bits
OrdinalConstantBit
0MON0
1TUE0
2WED0
3THU0
4FRI1 after add(FRI)
5SAT1
6SUN1
The whole set is one long: 112 after adding FRI.

So contains() is one shift and one AND, add() is one OR, and size() is a single bit-count instruction on modern CPUs. Set operations are just as cheap: addAll() between two RegularEnumSets of the same enum is one OR of two longs, retainAll() is one AND, and complementOf() flips the bits that belong to the enum. A HashSet doing the same work hashes each element, finds its bucket and walks nodes.

3How EnumMap Stores Values in an Array

EnumMap uses the same idea for maps. It keeps an Object[] with one slot per constant, so the value for a key is stored at index key.ordinal(). It also keeps the array of all constants, so it can turn an index back into a key during iteration.

Java
EnumMap<Day, Integer> hours = new EnumMap<>(Day.class);
hours.put(Day.MON, 8); // vals[0] = 8
hours.put(Day.FRI, 6); // vals[4] = 6
hours.get(Day.FRI); // vals[4] -> 6
hours.containsKey(Day.TUE); // vals[1] is empty -> false
System.out.println(hours); // {MON=8, FRI=6}

Notice that put() and get() are a single array access. EnumMap does allow null values, and uses an internal marker object to tell a stored null apart from an empty slot. It needs the enum's Class object, which is why the constructor takes Day.class: generics are erased at run time, so without it EnumMap would not know how many slots to create.

4Why They Beat HashSet and HashMap for Enum Keys

A HashMap must call hashCode() on each key, mix the bits, pick a bucket, compare with equals(), and allocate a node object of around 32 bytes per entry. An EnumMap for seven days holds one array of seven references and needs no per-entry objects at all. An EnumSet of up to 64 constants is a single long, 8 bytes of data, compared with a HashSet that wraps a HashMap with a node per element. The ordinal is already a perfect hash, so all that machinery is unnecessary.

The memory difference matters when sets are stored per entity, for example a set of permissions on each of a million users, and the speed difference matters in hot code such as routing or scheduling. Both are also simply clearer, because the type tells the reader the keys are enum constants.

Cost per operation with enum keys
OperationHashSet / HashMapEnumSet / EnumMap
contains / gethash, bucket, equals()one bit test or array read
add / puthash, bucket, maybe new nodeone OR or array write
Memory per entrya node of about 32 bytes1 bit, or one array slot
Iteration orderunspecifieddeclaration order
Null keysone allowed (HashMap)rejected

5Ordering, Nulls and Threads

Iteration over an EnumSet or an EnumMap always follows declaration order, because it walks the bits or the array from ordinal 0 upward. That is often useful, for example to print days in week order without sorting. The iterators are weakly consistent rather than fail-fast: modifying the collection during iteration does not throw ConcurrentModificationException, though it may or may not show the change.

Nulls are not allowed as members. EnumSet.add(null) and EnumMap.put(null, v) both throw NullPointerException, because null has no ordinal. And neither class is thread-safe. If several threads modify one, we wrap it, for example with Collections.synchronizedMap(new EnumMap<>(Day.class)), or we treat it as immutable after building it and publish it safely, which is the most common pattern for configuration-like data.

Java
EnumSet<Day> days = EnumSet.noneOf(Day.class);
days.add(null); // NullPointerException
Map<Day, Integer> shared = Collections.synchronizedMap(new EnumMap<>(Day.class));
Set<Day> fixed = Collections.unmodifiableSet(EnumSet.range(Day.MON, Day.FRI)); // [MON, TUE, WED, THU, FRI]

6Follow-up questions

Why is EnumSet an abstract class with factory methods instead of a constructor?

So it can choose the implementation at creation time. The factory methods look at the number of constants and return a RegularEnumSet or a JumboEnumSet, and callers never need to know which one they got.

Can EnumSet be used as a key in a HashMap?

Yes. It implements equals() and hashCode() as the Set contract requires, so two sets with the same constants are equal. But like any mutable key, it must not be changed while it is in the map.

Is EnumMap faster than a switch statement?

For a fixed mapping known at compile time, a switch is equally fast and needs no object. EnumMap wins when the mapping is built at run time, for example from configuration, or must be passed around as data.

7Conclusion

In this answer, we saw that EnumSet and EnumMap use the ordinal as a perfect index. EnumSet keeps one bit per constant, in a single long for up to 64 constants (RegularEnumSet) or a long array beyond that (JumboEnumSet), so contains, add and set operations are a few bit operations. EnumMap keeps values in an array indexed by ordinal. With no hashing, no node objects and no boxing they are faster and smaller than HashSet and HashMap, iterate in declaration order, reject null keys and elements, and are not thread-safe.

What to say in the interviewAbout 80 seconds aloud

Open with

Both rely on the fact that an enum's constants are fixed and each has a stable ordinal, which is a perfect hash. EnumSet is a bit vector. If the enum has up to 64 constants, the factory methods return a RegularEnumSet that holds a single long, where bit i is set when the constant with ordinal i is present.

Then, if they want more

Bigger enums get a JumboEnumSet with an array of longs. So contains is a shift and an AND, add is an OR, size is a bit count, and addAll or retainAll between two sets is one OR or AND.

EnumMap stores values in an Object array indexed by the key's ordinal, so put and get are one array access, and it needs the enum's Class in the constructor to size that array.

Compared with HashSet and HashMap there is no hashCode call, no bucket search, no equals, and no node object per entry, so they are faster and use far less memory. Iteration follows declaration order, which is often handy, and the iterators are weakly consistent rather than fail-fast.

Neither allows null keys or elements, EnumMap does allow null values, and neither is thread-safe, so I either wrap them or build them once and share them as unmodifiable.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "How are EnumSet and EnumMap implemented, and why are they faster than HashSet and...": https://scrivio-interview-library.netlify.app/java/enums/d15e97e98f/