Question
Why do I get a NullPointerException when I use EnumSet.add(enum) in Java?
EnumSet<Day> days = EnumSet.noneOf(Day.class);
days.add(null); // This line throws a NullPointerException.
Answer
The NullPointerException in this context usually stems from attempting to add a null value to an EnumSet. In Java, EnumSets are designed to work specifically with enum types and do not permit null elements due to their underlying implementation using bit vectors.
EnumSet<Day> days = EnumSet.of(Day.MONDAY, Day.TUESDAY);
// Attempting to add null here will lead to a NullPointerException.
if (day != null) {
days.add(day);
} else {
System.out.println("Cannot add null to an EnumSet.");
}
Causes
- Attempting to add a null value to an EnumSet, which doesn't allow null elements.
- The EnumSet is not initialized properly or is empty when trying to add elements.
Solutions
- Ensure that the enum value you are trying to add is not null before calling add().
- Initialize your EnumSet properly with valid enum types using EnumSet.of() or EnumSet.allOf() to avoid interacting with null values.
Common Mistakes
Mistake: Adding null elements directly to the EnumSet.
Solution: Always check that the enum value to be added is not null before calling add().
Mistake: Using EnumSet without proper initialization.
Solution: Use EnumSet.of() or EnumSet.allOf() to create and initialize the EnumSet with valid values.
Helpers
- Java EnumSet
- NullPointerException in Java
- Java EnumSet add method
- Fix NullPointerException Java