Course contentsShow
← Java
Lesson 598 of 2,87014. EnumerationsFree lesson

Creating EnumSets: Factory Methods Overview

Explore allOf, noneOf, of, range, and complementOf methods for creating EnumSet instances.

Creating EnumSets: Factory Methods Overview

What you'll learn: How to use EnumSet's factory methods to quickly create specialized sets of enum constants.

The Power of Factory Methods

Unlike most collections where you use new, EnumSet provides static factory methods that choose the most efficient internal implementation for you. Think of these methods as smart constructors that know exactly which variant of EnumSet to build based on your needs.

The Five Essential Factory Methods

EnumSet.allOf(Class) – Creates a set containing all constants from an enum type:

EnumSet<Day> allDays = EnumSet.allOf(Day.class);
// Contains all seven days

EnumSet.noneOf(Class) – Creates an empty set, ready to populate:

EnumSet<Day> noDays = EnumSet.noneOf(Day.class);
// Empty, but knows it holds Day values

EnumSet.of(...) – Creates a set with specific constants you list:

EnumSet<Day> weekend = EnumSet.of(Day.SATURDAY, Day.SUNDAY);

EnumSet.range(E from, E to) – Creates a set containing a contiguous range:

EnumSet<Day> weekdays = EnumSet.range(Day.MONDAY, Day.FRIDAY);
// Monday through Friday, inclusive

EnumSet.complementOf(EnumSet) – Creates a set with all constants not in the given set:

EnumSet<Day> notWeekend = EnumSet.complementOf(weekend);
// All days except Saturday and Sunday

Why These Methods Matter

Each method solves a common pattern efficiently. You never worry about capacity or hash codes—EnumSet handles everything internally using bit vectors, making these operations extremely fast.

Key Takeaway: EnumSet provides five factory methods—allOf, noneOf, of, range, and complementOf—that create optimized enum sets for every common initialization scenario without ever using new.