EnumSet in Java - GeeksforGeeks

17 Jan, 2022
Enumerations or popularly known as enum serve the purpose of representing a group of named constants in a programming language. For example, the 4 suits in a deck of playing cards may be 4 enumerators named Club, Diamond, Heart, and Spade, belonging to an enumerated type named Suit.
The EnumSet is one of the specialized implementations of the Set interface for use with the enumeration type. A few important features of EnumSet are as follows:
It extends AbstractSet class and implements Set Interface in Java.
EnumSet class is a member of the Java Collections Framework & 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.
The Hierarchy of EnumSet is as follows:
java.lang.Object
   ↳ java.util.AbstractCollection<E>
        ↳ java.util.AbstractSet<E>
             ↳ java.util.EnumSet<E>
Here, E is the type of elements stored.
Syntax: Declaration 
public abstract class EnumSet<E extends Enum<E>> 
Here, E specifies the elements. E must extend Enum, which enforces the requirement that the elements must be of the specified enum type.
Due to its implementation using RegularEnumSet and JumboEnumSet, all the methods in an EnumSet are implemented using bitwise arithmetic operations.
EnumSet is faster than HashSet because we no need to compute any hashCode to find the right bucket.
The computations are executed in constant time and the space required is very little.
Method
Action Performed 
Implementation:
Java
// Java Program to Illustrate Working// of EnumSet and its functions // Importing required classesimport java.util.EnumSet; // Enumenum Gfg { CODE, LEARN, CONTRIBUTE, QUIZ, MCQ }; // Main class// EnumSetExamplepublic class GFG {     // Main driver method    public static void main(String[] args) {         // Creating a set        EnumSet<Gfg> set1, set2, set3, set4;         // Adding elements        set1 = EnumSet.of(Gfg.QUIZ, Gfg.CONTRIBUTE,                          Gfg.LEARN, Gfg.CODE);        set2 = EnumSet.complementOf(set1);        set3 = EnumSet.allOf(Gfg.class);        set4 = EnumSet.range(Gfg.CODE, Gfg.CONTRIBUTE);         // Printing corresponding elements in Sets        System.out.println("Set 1: " + set1);        System.out.println("Set 2: " + set2);        System.out.println("Set 3: " + set3);        System.out.println("Set 4: " + set4);    }}
Set 1: [CODE, LEARN, CONTRIBUTE, QUIZ]
Set 2: [MCQ]
Set 3: [CODE, LEARN, CONTRIBUTE, QUIZ, MCQ]
Set 4: [CODE, LEARN, CONTRIBUTE]
Operation 1: Creating an EnumSet Object
Since EnumSet is an abstract class, we cannot directly create an instance of it. It has many static factory methods that allow us to create an instance. There are two different implementations of EnumSet provided by JDK 
RegularEnumSet
JumboEnumSet  
Note: These are package-private and backed by a bit vector.
RegularEnumSet uses a single long object to store elements of the EnumSet. Each bit of the long element represents an Enum value. Since the size of the long is 64 bits, it can store up to 64 different elements.
JumboEnumSet uses an array of long elements to store elements of the EnumSet. The only difference from RegularEnumSet is JumboEnumSet uses a long array to store the bit vector thereby allowing more than 64 values.
The factory methods create an instance based on the number of elements, EnumSet does not provide any public constructors, instances are created using static factory methods as listed below as follows:
allOf(size)
noneOf(size)
range(e1, e2)
of()            
Illustration:
if (universe.length <= 64)
    return new RegularEnumSet<>(elementType, universe);
else
    return new JumboEnumSet<>(elementType, universe);
Example:
Java
// Java Program to illustrate Creation an EnumSet // Importing required classesimport java.util.*; // Main class// CreateEnumSetclass GFG {     // Enum    enum Game { CRICKET, HOCKEY, TENNIS }     // Main driver method    public static void main(String[] args)    {         // Creating an EnumSet using allOf()        EnumSet<Game> games = EnumSet.allOf(Game.class);         // Printing EnumSet elements to the console        System.out.println("EnumSet: " + games);    }}
EnumSet: [CRICKET, HOCKEY, TENNIS]
Operation 2: Adding Elements
We can add elements to an EnumSet using add() and addAll() methods. 
Example:
Java
// Java program to illustrate Addition of Elements// to an EnumSet // Importing required classesimport java.util.EnumSet; // Main classclass AddElementsToEnumSet {     // Enum    enum Game { CRICKET, HOCKEY, TENNIS }     // Main driver method    public static void main(String[] args)    {         // Creating an EnumSet        // using allOf()        EnumSet<Game> games1 = EnumSet.allOf(Game.class);         // Creating an EnumSet        // using noneOf()        EnumSet<Game> games2 = EnumSet.noneOf(Game.class);         // Using add() method        games2.add(Game.HOCKEY);         // Printing the elements to the console        System.out.println("EnumSet Using add(): "                           + games2);         // Using addAll() method        games2.addAll(games1);         // Printing the elements to the console        System.out.println("EnumSet Using addAll(): "                           + games2);    }}
EnumSet Using add(): [HOCKEY]
EnumSet Using addAll(): [CRICKET, HOCKEY, TENNIS]
 Operation 3: Accessing Elements
We can access the EnumSet elements by using the iterator() method.
Example:
Java
// Java program to Access Elements of EnumSet // Importing required classesimport java.util.EnumSet;import java.util.Iterator; // Main class// AccessingElementsOfEnumSetclass GFG {     // Enum    enum Game { CRICKET, HOCKEY, TENNIS }     // MAin driver method    public static void main(String[] args)    {        // Creating an EnumSet using allOf()        EnumSet<Game> games = EnumSet.allOf(Game.class);         // Creating an iterator on games        Iterator<Game> iterate = games.iterator();         // Display message        System.out.print("EnumSet: ");         while (iterate.hasNext()) {             // Iterating and printing elements to            // the console using next() method            System.out.print(iterate.next());            System.out.print(", ");        }    }}
EnumSet: CRICKET, HOCKEY, TENNIS,
Operation 4: Removing elements
We can remove the elements using remove() and removeAll() methods.
Example:
Java
// Java program to Remove Elements// from a EnumSet // Importing required classesimport java.util.EnumSet; // Main class// RemovingElementsOfEnumSetclass GFG {     // Enum    enum Game { CRICKET, HOCKEY, TENNIS }     // Main driver method    public static void main(String[] args)    {        // Creating EnumSet using allOf()        EnumSet<Game> games = EnumSet.allOf(Game.class);         // Printing the EnumSet        System.out.println("EnumSet: " + games);         // Using remove()        boolean value1 = games.remove(Game.CRICKET);         // Printing elements to the console        System.out.println("Is CRICKET removed? " + value1);         // Using removeAll() and storing the boolean result        boolean value2 = games.removeAll(games);         // Printing elements to the console        System.out.println("Are all elements removed? "                           + value2);    }}
EnumSet: [CRICKET, HOCKEY, TENNIS]
Is CRICKET removed? true
Are all elements removed? true
Some other methods of classes or interfaces are defined below that somehow helps us to get a better understanding of AbstractSet Class as follows:
METHOD
DESCRIPTION
METHOD
DESCRIPTION
METHOD
DESCRIPTION
METHOD
DESCRIPTION
METHOD
DESCRIPTION
This article is contributed by Pratik Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on GeeksforGeek’s main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Chinmoy Lenka
vogtlcc
Ganeshchowdharysadanala
solankimayank
simranarora5sos
Java-Collections
java-EnumSet
Java-Library
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Reverse a string in Java
Arrays.sort() in Java with examples
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
How to iterate any Map in Java