What is EnumSet in java with example?

EnumSet in java with example

EnumSet in Java is a specialized implementation of the Set interface designed for use with enum types. It provides a high-performance set implementation that is specifically optimized for enums, offering better memory and performance characteristics compared to general-purpose set implementations like HashSet or TreeSet. Enum Set is particularly useful when working with a fixed set of enum constants and provides several advantages, such as type safety, compactness, and efficiency.

EnumSet

Here’s an example to illustrate the usage of Enum Set in Java:

java

import java.util.Enum Set;

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

public class Enum SetExample {
    public static void main(String[] args) {
        // Create an Enum Set for days of the week
        EnumSet<Day> weekdays = EnumSet.of(Day.MONDAY, Day.TUESDAY, Day.WEDNESDAY, Day.THURSDAY, Day.FRIDAY);
        
        // Add more days to the Enum Set
        weekdays.add(Day.SATURDAY);
        weekdays.add(Day.SUNDAY);
        
        // Print the contents of the Enum Set
        System.out.println("Days in the Enum Set:");
        for (Day day : weekdays) {
            System.out.println(day);
        }
        
        // Check if a specific day is present in the Enum Set
        System.out.println("Is SATURDAY present? " + weekdays.contains(Day.SATURDAY));
        System.out.println("Is SUNDAY present? " + weekdays.contains(Day.SUNDAY));
        
        // Remove a day from the EnumSet
        weekdays.remove(Day.SUNDAY);
        
        // Print the updated contents of the Enum Set
        System.out.println("Updated days in the EnumSet:");
        for (Day day : weekdays) {
            System.out.println(day);
        }
    }
}

Enum Example

In this example, we define an enum called Day representing the days of the week. We then create an Enum Set named weekdays using the Enum Set.of() method, which adds the specified enum constants to the set. We add additional days to the Enum Set using the add() method and iterate over the elements of the set using a for-each loop. We also demonstrate checking for the presence of specific constants, removing elements from the Set, and printing the updated contents of the set. Its provides a concise and efficient way to work with a fixed set of enum constants in Java.

Homepage

Readmore