In Java, the EnumSet is a specialized set implementation for use with enum types. It is a part of java.util package and provides a highly optimized set for storing enum constants. The EnumSet is one of the specialized implementations of the Set interface for use with the enumeration type.
- It extends the AbstractSet class and implements the Set Interface in Java.
- The EnumSet class is a member of the Java Collections Framework and is not synchronized.
- It’s a high-performance set implementation, much faster than HashSet.
- All of the elements in an EnumSet must come from a single enumeration type that is specified when the set is created either explicitly or implicitly.
- It does not allow null Objects and throws NullPointerException if we do so.
- It uses a fail-safe iterator, so it won’t throw ConcurrentModificationException if the collection is modified while iterating.
Example: This example demonstrates how to create an EnumSet and print its elements
// Creating an EnumSet
import java.util.EnumSet;
enum Student { Geek1, Geek2, Geek3, Geek4, Geek5 }
public class Geeks {
public static void main(String[] args) {
// Create an EnumSet containing specific elements
EnumSet<Student> e = EnumSet.of(Student.Geek1, Student.Geek2, Student.Geek3);
System.out.println("EnumSet: " + e);
}
}
Output
EnumSet: [Geek1, Geek2, Geek3]
Hierarchy of EnumSet
The Hierarchy of EnumSet is as follows: