What is EnumSet?

QuestionsQuestions8 SkillsProJava Enum FundamentalsSep, 20 2025
0133

EnumSet is a specialized set implementation in Java that is designed specifically for use with enum types. It is part of the java.util package and provides a high-performance way to work with sets of enum constants. Here are some key features of EnumSet:

  1. Type-Safe: EnumSet is type-safe, meaning it can only contain enum constants of a specific enum type.

  2. Efficient: It is implemented as a bit vector, making it very efficient in terms of memory and performance compared to other set implementations.

  3. Flexible: You can create EnumSet instances using various methods:

    • EnumSet.noneOf(Class<E> elementType): Creates an empty set.
    • EnumSet.allOf(Class<E> elementType): Creates a set containing all the constants of the specified enum type.
    • EnumSet.of(E e): Creates a set containing a single specified enum constant.
    • EnumSet.of(E e1, E e2, E... rest): Creates a set containing multiple specified enum constants.
  4. Operations: It supports standard set operations like union, intersection, and difference.

Here’s a simple example of using EnumSet:

import java.util.EnumSet;

enum StudentResult {
    PASS,
    FAIL,
    ABSENT;
}

public class Demo {
    public static void main(String[] args) {
        EnumSet<StudentResult> resultSet = EnumSet.of(StudentResult.PASS, StudentResult.FAIL);
        System.out.println("Result Set: " + resultSet);
    }
}

In this example, resultSet contains the PASS and FAIL constants from the StudentResult enum.

0 Comments

no data
Be the first to share your comment!