EnumMap and EnumSet
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)An enum (see Enum basics (opens in a new tab)) is a type with a fixed set of constants, such as the status of an order or a day of the week. When the keys of a map, or the elements of a set, are the constants of one enum, Java has two special classes for it: EnumMap and EnumSet. They are smaller, faster and tidier than HashMap and HashSet.
What you will learn
- Use an EnumMap when the keys are constants of one enum
- Create an EnumSet with of, range, allOf, noneOf and complementOf
- Explain why EnumMap and EnumSet are fast and keep declaration order
- Avoid the null-key and constructor mistakes
- Choose between EnumMap and HashMap for enum keys
Topics in this lesson
- EnumMap: a map keyed by an enum
- Counting and grouping with enum keys
- EnumSet: a set of enum constants
- EnumMap or HashMap? Limits and traps
Key points
EnumMapandEnumSetare for keys and elements that are constants of one enum; they are fast and loop in declaration order.- Create an
EnumMapwith the enum class:new EnumMap<>(Day.class); create anEnumSetwithof,range,allOf,noneOforcomplementOf. OrderStatus.values()plusgetOrDefaultprints every constant, even those with no entry.- Neither accepts
nullkeys or elements, and neither is thread-safe.
Interview questions this lesson answers
- What is an
EnumMap, and when would you use it? - Why does
new EnumMap<>(Day.class)need the class? - Can an
EnumMaporEnumSetholdnull? - How do you create an
EnumSet? - Why prefer
EnumMaptoHashMapfor enum keys? - What is the order of an
EnumSetorEnumMaploop? - Follow-up: how do you list the days that are not in an
EnumSet?
Sign in to continue this lesson
Create an account to read every lesson, practise with the exercises and keep track of your progress.