EnumSet Operations: Add, Remove, and Bulk Modifications
What you'll learn: How to manipulate EnumSets using standard Set operations and why they're more efficient than regular Sets.
Core Operations
Since EnumSet implements the Set interface, it provides all familiar Set methods—but executes them far more efficiently thanks to its bit vector implementation.
Adding elements:
enum Day { MON, TUE, WED, THU, FRI, SAT, SUN }
EnumSet<Day> workDays = EnumSet.noneOf(Day.class);
workDays.add(Day.MON);
workDays.add(Day.TUE);
workDays.add(Day.WED);
// Returns true if the set changed
Removing elements:
EnumSet<Day> weekend = EnumSet.of(Day.SAT, Day.SUN, Day.MON);
weekend.remove(Day.MON); // Returns true (was present)
weekend.remove(Day.TUE); // Returns false (wasn't there)
Bulk Operations: Where EnumSet Shines
The real power comes with bulk modifications—operations that work on multiple elements at once:
EnumSet<Day> schedule = EnumSet.of(Day.MON, Day.WED);
EnumSet<Day> moreDays = EnumSet.of(Day.TUE, Day.THU);
// Add multiple elements
schedule.addAll(moreDays); // Now: MON, TUE, WED, THU
// Remove multiple elements
schedule.removeAll(EnumSet.of(Day.MON, Day.TUE)); // Now: WED, THU
// Keep only elements in both sets
schedule.retainAll(EnumSet.of(Day.THU, Day.FRI)); // Now: only THU
Why It's Fast
These operations use bitwise arithmetic internally. Adding elements? It's just an OR operation. Removing? AND with complement. This makes bulk operations nearly instantaneous, regardless of how many elements you're manipulating—a stark contrast to HashSet's element-by-element approach.
Key Takeaway: EnumSet supports all standard Set operations (add, remove, addAll, removeAll, retainAll) but executes them dramatically faster through bit manipulation, making it ideal for flag-like operations or when working with multiple enum constants simultaneously.