Java EnumSet Methods Example

In this source code example, we will show you the usage of important Java EnumSet class methods with examples.

EnumSet is a specialized Set implementation for use with enum types. It's part of the java.util package. Being a highly efficient, compact alternative to traditional sets, it is designed to provide all of the richness of the traditional Set interface without the time and space overheads.

Java EnumSet Class Important Methods 

import java.util.EnumSet;

// Define an enumeration for days of the week
enum Day {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}

public class EnumSetDemo {
    public static void main(String[] args) {
        // 1. Initialization using allOf
        EnumSet<Day> allDays = EnumSet.allOf(Day.class);
        System.out.println("All days: " + allDays);

        // 2. Initialization using noneOf
        EnumSet<Day> noDays = EnumSet.noneOf(Day.class);
        System.out.println("No days: " + noDays);

        // 3. Initialization with specific days
        EnumSet<Day> weekend = EnumSet.of(Day.SATURDAY, Day.SUNDAY);
        System.out.println("Weekend days: " + weekend);

        // 4. Initialization with a range
        EnumSet<Day> weekdays = EnumSet.range(Day.MONDAY, Day.FRIDAY);
        System.out.println("Weekdays: " + weekdays);

        // 5. Using complementOf to get the opposite of a specific set
        EnumSet<Day> notWeekend = EnumSet.complementOf(weekend);
        System.out.println("Not weekend days: " + notWeekend);
    }
}

Output:

All days: [MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY]
No days: []
Weekend days: [SATURDAY, SUNDAY]
Weekdays: [MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY]
Not weekend days: [MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY]

Explanation:

1. allOf: Creates an EnumSet containing all the constants of the specified enumeration class.

2. noneOf: Creates an empty EnumSet with the specified element type.

3. of: Creates an EnumSet with the specified constants. Here, it's used to initialize the weekend with SATURDAY and SUNDAY.

4. range: Creates an EnumSet ranging from the specified constant start to end. Here, it's used to create a set with all weekdays.

5. complementOf: Creates an EnumSet with elements not present in the specified set. In this case, it returns all days except the weekend.


Comments