Video in progress
What is the internal structure of EnumMap and EnumSet, and why are they faster than HashMap/HashSet?
Both are built on ordinal(): EnumMap is a plain array indexed by ordinal, and EnumSet is a bit vector (a single long for up to 64 constants). There's no hash, no bucket, and no boxing.
📖 Answer
The number of enum values is known in advance, and each one has an ordinal in the range 0..n-1. That fact makes a hash table unnecessary.
enum Perm { READ, WRITE, DELETE, ADMIN }
EnumSet<Perm> p = EnumSet.of(Perm.READ, Perm.WRITE);
// inside: long elements = 0b0011
p.contains(Perm.WRITE); // (elements & (1L << 1)) != 0
EnumMap<Perm, Integer> counts = new EnumMap<>(Perm.class);
// inside: Object[] vals = new Object[4]; vals[ordinal] = value
As a result, contains, add and get come down to a single bit operation or an array index. Also:
- iteration always follows the order in which the enum is declared;
- memory use is tiny: an
EnumSetwith up to 64 elements (RegularEnumSet) is a singlelong, and a bigger one is aJumboEnumSet(long[]); containsAllandretainAllalso work with bit operations.
The limitations: you can't use a null key (EnumMap does allow a null value), and neither is thread-safe.
One trap: values() returns a new copy of the array on every call. If you write Perm.values()[i] in a hot loop, you get needless allocation: keep the array in a static final field.
Sign up to mark studied questions and save your progress.