EnumMap and EnumSet
Use the array-backed collections that exist only for enum keys and enum elements.
Open this lesson in the learning hubKey points
EnumMapis a plain array indexed byordinal(). No hashing, no collisions, no entry objects.- It always iterates in enum declaration order, whatever order you inserted things in.
EnumSetis a bit vector, usually onelong, socontainsis a single bit test.- Factories read well:
EnumSet.of,allOf,noneOf,range,complementOf. - Both reject
null, and both are dramatically smaller and faster than the hash-based equivalents. - If the key type is an enum, these are the default choice rather than an optimisation.
Example
import java.util.*;
public class Main {
enum Day { MON, TUE, WED, THU, FRI, SAT, SUN }
public static void main(String[] args) {
EnumMap<Day, String> plan = new EnumMap<>(Day.class);
plan.put(Day.WED, "ship");
plan.put(Day.MON, "plan");
plan.put(Day.FRI, "review");
System.out.println("EnumMap : " + plan);
System.out.println("inserted WED first, printed in declaration order");
System.out.println("WED.ordinal() : " + Day.WED.ordinal() + " (that is its array slot)");
EnumSet<Day> weekend = EnumSet.of(Day.SAT, Day.SUN);
System.out.println("EnumSet.of : " + weekend);
System.out.println("complementOf : " + EnumSet.complementOf(weekend));
System.out.println("range(MON, WED) : " + EnumSet.range(Day.MON, Day.WED));
System.out.println("allOf size : " + EnumSet.allOf(Day.class).size());
System.out.println("noneOf : " + EnumSet.noneOf(Day.class));
System.out.println("contains(SAT) : " + weekend.contains(Day.SAT) + " (one bit test)");
EnumSet<Day> busy = EnumSet.copyOf(plan.keySet());
busy.removeAll(weekend);
System.out.println("busy weekdays : " + busy);
}
}
Enum keys have their own collections, and they beat HashMap on both speed and memory.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Collections course, and every lesson in it is listed on the Collections contents page.