Java Zero to All All questionsPractise free
Interview questions › Java Foundations — Zero to Basics › OOP III — Encapsulation, Abstraction, Enums

Why should you prefer EnumMap and EnumSet over HashMap and HashSet when keys are enums?

Level II · JuniorOOP III — Encapsulation, Abstraction, Enums
Short answer

EnumSet is internally a bit vector and EnumMap is backed by a plain array indexed by the enum's ordinal, so both are dramatically faster and more memory-efficient than the hash-based versions and need no hashing or boxing.

Explanation

They also iterate in natural (declaration) order, which is often what you want. The only caveat is that they're tied to a single enum type and are not thread-safe, so wrap them if shared across threads.

Common mistakes
  • Not knowing EnumMap is array-backed and faster with ordered iteration.
  • Using HashSet<Enum> where EnumSet is smaller and faster.

Can you say this out loud in two minutes? Drill it in a timed mock interview, with flashcards and runnable code for OOP III — Encapsulation, Abstraction, Enums.

Practise free

More on OOP III — Encapsulation, Abstraction, Enums