Sub topic 4
EnumSet and EnumMap
So far you have used enum constants one at a time. Real programs often need groups of them. You might need "the days the shop is open" or "how many hours someone worked each day". Java has two collections built for this job: EnumSet and EnumMap.
A collection is an object that holds a group of other objects. You may already know HashSet and HashMap. They work with enums, but the enum versions are smaller, faster, and keep a predictable order.
This chapter uses the Day enum from earlier chapters:
enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }What Is an EnumSet?
A set is a collection with no duplicates. Each item is either in the set or not in it. An EnumSet is a set that can only hold constants from one enum type.
You never write new EnumSet<>(). Instead, you call a static factory method, which is a method on the class that builds the object for you. Here are the most useful ones:
| Method | What it gives you |
|---|---|
| `EnumSet.of(a, b, ...)` | A set with exactly the constants you list |
| `EnumSet.noneOf(Day.class)` | An empty set that can hold `Day` constants |
| `EnumSet.allOf(Day.class)` | A set with every constant of the enum |
| `EnumSet.range(from, to)` | All constants from `from` to `to`, both included |
| `EnumSet.complementOf(set)` | Every constant that is not in `set` |
| `EnumSet.copyOf(collection)` | A new set with the same constants as another collection |
Day.class is a class literal. It is an object that stands for the type Day. An empty set has no constants to look at, so Java can't work out the enum type without it.
A Worked Example
Save this as Main.java, then compile and run it:
import java.util.EnumSet;
enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
public class Main {
public static void main(String[] args) {
EnumSet<Day> weekend = EnumSet.of(Day.SATURDAY, Day.SUNDAY);
EnumSet<Day> weekdays = EnumSet.complementOf(weekend);
EnumSet<Day> midweek = EnumSet.range(Day.TUESDAY, Day.THURSDAY);
EnumSet<Day> everyDay = EnumSet.allOf(Day.class);
EnumSet<Day> shopOpen = EnumSet.noneOf(Day.class);
System.out.println("Weekend: " + weekend);
System.out.println("Weekdays: " + weekdays);
System.out.println("Midweek: " + midweek);
System.out.println("All: " + everyDay.size() + " days");
shopOpen.add(Day.SATURDAY);
shopOpen.add(Day.MONDAY);
shopOpen.add(Day.MONDAY); // duplicate, ignored
System.out.println("Shop open: " + shopOpen);
System.out.println(shopOpen.contains(Day.SUNDAY)); // false
System.out.println(weekend.contains(Day.SUNDAY)); // true
}
}The output is:
Weekend: [SATURDAY, SUNDAY]
Weekdays: [MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY]
Midweek: [TUESDAY, WEDNESDAY, THURSDAY]
All: 7 days
Shop open: [MONDAY, SATURDAY]
false
trueLook at the "Shop open" line. We added SATURDAY first, but MONDAY is printed first. An EnumSet always lists constants in declaration order, which is the order you wrote them in the enum. The order you added them doesn't matter.
Set Operations
An EnumSet is a normal Set, so it has all the usual set methods. Three of them are worth learning by name:
addAll(other)is a union. It adds everything fromother.retainAll(other)is an intersection. It keeps only what both sets share.removeAll(other)is a difference. It removes everything that is inother.
These methods change the set you call them on. To keep the original, make a copy first with EnumSet.copyOf(set).
What Is an EnumMap?
A map stores pairs. Each pair has a key, which you look up by, and a value, which is the data stored for that key. An EnumMap is a map whose keys must be constants from one enum.
You create one with a constructor and pass the enum's class literal:
import java.util.EnumMap;
import java.util.Map;
enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
public class Main {
public static void main(String[] args) {
EnumMap<Day, Integer> hours = new EnumMap<>(Day.class);
hours.put(Day.FRIDAY, 4);
hours.put(Day.MONDAY, 8);
hours.put(Day.TUESDAY, 6);
System.out.println(hours); // {MONDAY=8, TUESDAY=6, FRIDAY=4}
System.out.println(hours.get(Day.MONDAY)); // 8
System.out.println(hours.get(Day.SUNDAY)); // null
System.out.println(hours.getOrDefault(Day.SUNDAY, 0)); // 0
hours.merge(Day.MONDAY, 2, Integer::sum); // add 2 more hours
System.out.println(hours.get(Day.MONDAY)); // 10
int total = 0;
for (Map.Entry<Day, Integer> entry : hours.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
total += entry.getValue();
}
System.out.println("Total: " + total); // Total: 20
}
}The map keeps declaration order too. We put FRIDAY first, but it prints last.
Two methods in this example need explaining:
getOrDefault(key, fallback)returns the value for the key. If the key has no value, it returnsfallback. This avoids gettingnullback.merge(key, value, Integer::sum)putsvaluein if the key is missing. If the key is already there, it adds the old value and the new one together.Integer::sumis a method reference, which is a short way to pass an existing method as an argument. It is a common way to count or total things in a map.
Nesting the Two
You can put an EnumSet inside an EnumMap. Here is a schedule that maps each day to the shifts that are staffed:
import java.util.EnumMap;
import java.util.EnumSet;
enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
enum Shift { MORNING, AFTERNOON, NIGHT }
public class Main {
public static void main(String[] args) {
EnumMap<Day, EnumSet<Shift>> schedule = new EnumMap<>(Day.class);
for (Day d : Day.values()) {
schedule.put(d, EnumSet.noneOf(Shift.class));
}
schedule.get(Day.MONDAY).add(Shift.MORNING);
schedule.get(Day.MONDAY).add(Shift.NIGHT);
schedule.get(Day.SATURDAY).addAll(EnumSet.allOf(Shift.class));
System.out.println(schedule.get(Day.MONDAY)); // [MORNING, NIGHT]
System.out.println(schedule.get(Day.SATURDAY)); // [MORNING, AFTERNOON, NIGHT]
System.out.println(schedule.get(Day.SUNDAY)); // []
}
}How They Work Inside
Every enum constant has an ordinal, its position number starting at 0. Both collections use the ordinal to do their work quickly.
An EnumSet for a small enum is stored as one long number. A long has 64 bits, and each bit is a single 0 or 1. Bit 0 says whether MONDAY is in the set, bit 1 says whether TUESDAY is, and so on. Checking contains only means reading one bit, which is very fast. Enums with more than 64 constants use an array of long values instead, and they are still fast.
An EnumMap is stored as an array. The value for MONDAY sits at index 0, the value for TUESDAY at index 1, and so on. Looking up a key means going straight to one array slot. Nothing has to be hashed or searched.
This design explains why both collections keep declaration order. They simply walk through the bits or the array slots from 0 upward.
Comparing with HashSet and HashMap
| Feature | HashSet / HashMap | EnumSet / EnumMap |
|---|---|---|
| Allowed keys or elements | Any object | Constants of one enum only |
| Iteration order | No promised order | Declaration order |
| Memory | An object for each entry | One bit or one array slot per constant |
| Speed | Fast | Faster, with no hashing |
| `null` keys or elements | Allowed | Not allowed |
Edge Cases and Common Mistakes
These collections have a few rules that catch beginners. This program shows each one:
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.List;
enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
public class Main {
public static void main(String[] args) {
EnumSet<Day> days = EnumSet.noneOf(Day.class);
try {
days.add(null);
} catch (NullPointerException e) {
System.out.println("EnumSet rejects null elements");
}
EnumMap<Day, String> notes = new EnumMap<>(Day.class);
notes.put(Day.MONDAY, null); // a null VALUE is fine
System.out.println(notes.containsKey(Day.MONDAY)); // true
try {
notes.put(null, "hello");
} catch (NullPointerException e) {
System.out.println("EnumMap rejects null keys");
}
List<Day> empty = new ArrayList<>();
try {
EnumSet.copyOf(empty);
} catch (IllegalArgumentException e) {
System.out.println("copyOf cannot copy an empty plain collection");
}
try {
EnumSet.range(Day.FRIDAY, Day.MONDAY);
} catch (IllegalArgumentException e) {
System.out.println("range needs from <= to");
}
}
}Each rule, in plain words:
- No
nullelements or keys. Anullhas no ordinal, so there is no bit or slot to put it in.EnumMapdoes allownullas a value. copyOfon an empty list fails. An emptyListhas no constants, so Java can't tell which enum you mean. UseEnumSet.noneOf(Day.class)instead. Copying anotherEnumSet, even an empty one, works, because that set already knows its type.rangemust go forward. The first constant must not come after the second in declaration order.- Not thread-safe. Thread-safe means several threads (parts of a program running at the same time) can use the object safely together. These collections aren't. If threads share one, wrap it with
Collections.synchronizedSetorCollections.synchronizedMap.
Exercises
Exercise
You run EnumSet<Day> s = EnumSet.noneOf(Day.class); s.add(Day.SUNDAY); s.add(Day.WEDNESDAY); System.out.println(s);. What is printed, and why?
Show answer
It prints [WEDNESDAY, SUNDAY]. An EnumSet always lists constants in declaration order, and WEDNESDAY is declared before SUNDAY in the Day enum. The order you added them doesn't matter.
Exercise
Write one line that creates an EnumSet called workdays holding MONDAY through FRIDAY, without listing each day by name.
Show answer
EnumSet<Day> workdays = EnumSet.range(Day.MONDAY, Day.FRIDAY); You could also write EnumSet.complementOf(EnumSet.of(Day.SATURDAY, Day.SUNDAY)).
Exercise
You have a List<Day> called visits, where each item is the day a customer came in. Write a loop that counts the visits per day in an EnumMap<Day, Integer> called counts.
Show answer
EnumMap<Day, Integer> counts = new EnumMap<>(Day.class); for (Day d : visits) { counts.merge(d, 1, Integer::sum); } The merge call puts 1 in the map the first time a day appears and adds 1 to the old count each time after that.
Exercise
A teammate writes EnumSet<Day> copy = EnumSet.copyOf(someList); and it sometimes throws IllegalArgumentException. What causes this, and how can they fix it?
Show answer
copyOf throws when someList is an empty plain collection, because Java can't tell which enum type to use. One fix: EnumSet<Day> copy = EnumSet.noneOf(Day.class); copy.addAll(someList); This works whether or not the list is empty.