The Wayback Machine - https://web.archive.org/web/20240828102710/https://www.geeksforgeeks.org/enumset-class-java/
Open In App

EnumSet in Java

Last Updated : 28 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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:

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.

EnumSet in Java Collection

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.

Benefits of using EnumSet

  • 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.

Methods of EnumSet

Method

Action Performed 

allOf(Class<E> elementType)Creates an enum set containing all of the elements in the specified element type.
clone()Returns a copy of this set.
complementOf(EnumSet<E> s)Creates an enum set with the same element type as the specified enum set, initially containing all the elements of this type that are not contained in the specified set.
copyOf(Collection<E> c)Creates an enum set initialized from the specified collection.
copyOf(EnumSet<E> s)Creates an enum set with the same element type as the specified enum set, initially containing the same elements (if any).
noneOf(Class<E> elementType)Creates an empty enum set with the specified element type.
of(E e)Creates an enum set initially containing the specified element.
of(E e1, E e2)Creates an enum set initially containing the specified elements.
of(E first, E… rest)Creates an enum set initially containing the specified elements.
of(E e1, E e2, E e3)Creates an enum set initially containing the specified elements.
of(E e1, E e2, E e3, E e4)Creates an enum set initially containing the specified elements.
of(E e1, E e2, E e3, E e4, E e5)Creates an enum set initially containing the specified elements.
range(E from, E to)Creates an enum set initially containing all of the elements in the range defined by the two specified endpoints.

Implementation:

Java
// Java Program to Illustrate Working
// of EnumSet and its functions

// Importing required classes
import java.util.EnumSet;

// Enum
enum Gfg { CODE, LEARN, CONTRIBUTE, QUIZ, MCQ };

// Main class
// EnumSetExample
public 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);
    }
}

Output
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:

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 classes
import java.util.*;

// Main class
// CreateEnumSet
class 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);
    }
}

Output
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 classes
import java.util.EnumSet;

// Main class
class 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);
    }
}

Output
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 classes
import java.util.EnumSet;
import java.util.Iterator;

// Main class
// AccessingElementsOfEnumSet
class 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(", ");
        }
    }
}

Output
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 classes
import java.util.EnumSet;

// Main class
// RemovingElementsOfEnumSet
class 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);
    }
}

Output
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:

Methods declared in class java.util.AbstractSet

METHOD

DESCRIPTION

equals(Object o)Compares the specified object with this set for equality.
 hashCode()Returns the hash code value for this set.
removeAll(Collection<?> c)Removes from this set all of its elements that are contained in the specified collection (optional operation).

Methods declared in interface java.util.Collection

METHOD

DESCRIPTION

parallelStream()Returns a possibly parallel Stream with this collection as its source.
removeIf(Predicate<? super E> filter)Removes all of the elements of this collection that satisfy the given predicate.
stream()Returns a sequential Stream with this collection as its source.
toArray(IntFunction<T[]> generator)Returns an array containing all of the elements in this collection, using the provided generator function to allocate the returned array.

Methods declared in interface java.lang.Iterable

METHOD

DESCRIPTION

forEach(Consumer<? super T> action)Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.

Methods declared in interface java.util.Set

METHOD

DESCRIPTION

add(E e)Adds the specified element to this set if it is not already present (optional operation). 
addAll(Collection<? extends E> c) Adds the specified element to this set if it is not already present (optional operation).
 clear()Removes all of the elements from this set (optional operation).
 contains(Object o)Returns true if this set contains the specified element. 
containsAll(Collection<?> c) Returns true if this set contains all of the elements of the specified collection.
 isEmpty()Returns true if this set contains no elements.
 iterator()Returns an iterator over the elements in this set.
remove(Object o)Removes the specified element from this set if it is present (optional operation).
retainAll(Collection<?> c) Retains only the elements in this set that are contained in the specified collection (optional operation).
size()Returns the number of elements in this set (its cardinality).
spliterator()Creates a Spliterator over the elements in this set.
toArray()Returns an array containing all of the elements in this set.
toArray(T[] a)Returns an array containing all of the elements in this set; the runtime type of the returned array is that of the specified array.

Methods declared in class java.util.AbstractCollection

METHOD

DESCRIPTION

 add(E e)Ensures that this collection contains the specified element (optional operation).
 addAll(Collection<? extends E> c)Adds all of the elements in the specified collection to this collection (optional operation).
clear()Removes all of the elements from this collection (optional operation).
contains(Object o)Returns true if this collection contains the specified element.
containsAll(Collection<?> c)Returns true if this collection contains all of the elements in the specified collection.
isEmpty()Returns true if this collection contains no elements.
iterator()Returns an iterator over the elements contained in this collection.
remove(Object o)Removes a single instance of the specified element from this collection, if it is present (optional operation).
retainAll(Collection<?> c)Retains only the elements in this collection that are contained in the specified collection (optional operation).
 toArray()Returns an array containing all of the elements in this collection.
toArray(T[] a)Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array.
 toString()Returns a string representation of this collection.

See your article appearing on GeeksforGeek’s main page and help other Geeks.



Similar Reads

EnumSet of() Method in Java
The java.util.EnumSet.of(E ele1, E ele2, E ele3, ...) method in Java is used to create an enum set initially containing the specified elements in the parameters. When multiple items are added at the same time the elements are pushed down the set as the new elements are added. When different elements are added at different time or iteration, the old
5 min read
EnumSet clone() Method in Java
The Java.util.EnumSet.clone() method in Java is used to return a shallow copy of the existing or this set. Syntax: Enum_Set_2 = Enum_Set_1.clone() Parameters: The method does not take any parameters. Return Value: The method does not return any value. Below programs illustrate the working of Java.util.EnumSet.clone() method: Program 1: // Java prog
2 min read
EnumSet complementOf() Method in Java
The java.util.EnumSet.complementOf(Enum_Set) method is used to create an EnumSet containing elements of the same type as that of the specified Enum_Set, with the values present in the enum but other than those contained in the specified Enum_Set. Syntax: New_Enum_Set = EnumSet.complementOf(Enum_Set) Parameters: The method accepts one parameter Enum
2 min read
EnumSet allof() Method in Java
The Java.util.EnumSet.allOf(Class elementType) in Java is used to create an enum set that will be used to contain all of the elements in the specified elementType. Syntax: public static > EnumSet allOf(Class elementType) Parameters: The method accepts one parameter elementType of element type and refers to the class object whose elements are to be
2 min read
EnumSet copyOf() Method in Java
The java.util.EnumSet.copyOf(Collection collect) method in Java is used to copy all of the contents from a collection to a new enum set. At first, the collection is made out of the elements of the enum and then a new enum set is created, which is the copy of the collection. Syntax: New_Enum_Set = EnumSet.copyOf(Collection collect) Parameters: The m
3 min read
EnumSet noneOf() Method in Java
The java.util.EnumSet.noneOf(Class elementType) method in Java is used to create a null set of the type elementType. Syntax: public static &lt;E extends Enum&lt;E&gt;&gt; EnumSet&lt;E&gt; noneOf(Class&lt;E&gt; elementType) Parameters: The method accepts one parameter elementType of element type and refers to the class object of the element type for
2 min read
EnumSet range() Method in Java
The java.util.EnumSet.range(E start_point, E end_point) method in Java is used to create an enum set with the elements defined by the specified range in the parameters. Syntax: Enum_set = EnumSet.range(E start_point, E end_point) Parameters: The method accepts two parameters of the object type of enum: start_point: This refers to the starting eleme
2 min read
Difference Between EnumMap and EnumSet in Java
EnumMap and EnumSet both are the classes defined inside the java collection. In this article, we will learn the differences between EnumMap and EnumSet. EnumMap is the specialized implementation of the Map interface and the EnumSet is the specialized implementation of the Set interface. There are some differences that exist between them. So we have
3 min read
Difference Between EnumSet and TreeSet in Java
EnumSet and TreeSet both are the classes defined inside the collection framework. But there are few differences exists between them. In this article, we have tried to cover all these differences between them. 1. EnumSet: EnumSet is a specialized implementation of the Set interface for enumeration types. It extends AbstractSet and implements the Set
3 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Java AWT vs Java Swing vs Java FX
Java's UI frameworks include Java AWT, Java Swing, and JavaFX. This plays a very important role in creating the user experience of Java applications. These frameworks provide a range of tools and components for creating graphical user interfaces (GUIs) that are not only functional but also visually appealing. As a Java developer, selecting the righ
11 min read
Java.io.ObjectInputStream Class in Java | Set 2
Java.io.ObjectInputStream Class in Java | Set 1 Note : Java codes mentioned in this article won't run on Online IDE as the file used in the code doesn't exists online. So, to verify the working of the codes, you can copy them to your System and can run it over there. More Methods of ObjectInputStream Class : defaultReadObject() : java.io.ObjectInpu
6 min read
Java.lang.Class class in Java | Set 1
Java provides a class with name Class in java.lang package. Instances of the class Class represent classes and interfaces in a running Java application. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects. It has no public constructor. Class objects are cons
15+ min read
Java.lang.StrictMath class in Java | Set 2
Java.lang.StrictMath Class in Java | Set 1More methods of java.lang.StrictMath class 13. exp() : java.lang.StrictMath.exp(double arg) method returns the Euler’s number raised to the power of double argument. Important cases: Result is NaN, if argument is NaN.Result is +ve infinity, if the argument is +ve infinity.Result is +ve zero, if argument is
6 min read
java.lang.instrument.ClassDefinition Class in Java
This class is used to bind together the supplied class and class file bytes in a single ClassDefinition object. These class provide methods to extract information about the type of class and class file bytes of an object. This class is a subclass of java.lang.Object class. Class declaration: public final class ClassDefinition extends ObjectConstruc
2 min read
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap also contains functions that support retrieval and deletion at both, high and low end of values and hence give a lot of flexibility in applicability and daily use. This function is poll() and has 2 variants discussed in this article. 1. pollFirstEntry() : It removes and retrieves a key-value pair with the least key value in the ma
4 min read
Java.util.TreeMap.floorEntry() and floorKey() in Java
Finding greatest number less than given value is used in many a places and having that feature in a map based container is always a plus. Java.util.TreeMap also offers this functionality using floor() function. There are 2 variants, both are discussed below. 1. floorEntry() : It returns a key-value mapping associated with the greatest key less than
3 min read
java.lang.Math.atan2() in Java
atan2() is an inbuilt method in Java that is used to return the theta component from the polar coordinate. The atan2() method returns a numeric value between -[Tex]\pi [/Tex]and [Tex]\pi [/Tex]representing the angle [Tex]\theta [/Tex]of a (x, y) point and the positive x-axis. It is the counterclockwise angle, measured in radian, between the positiv
1 min read
java.net.URLConnection Class in Java
URLConnection Class in Java is an abstract class that represents a connection of a resource as specified by the corresponding URL. It is imported by the java.net package. The URLConnection class is utilized for serving two different yet related purposes, Firstly it provides control on interaction with a server(especially an HTTP server) than URL cl
5 min read
Java 8 | ArrayDeque removeIf() method in Java with Examples
The removeIf() method of ArrayDeque is used to remove all those elements from ArrayDeque which satisfies a given predicate filter condition passed as a parameter to the method. This method returns true if some element are removed from the Vector. Java 8 has an important in-built functional interface which is Predicate. Predicate, or a condition che
3 min read
Java.util.GregorianCalendar Class in Java
Prerequisites : java.util.Locale, java.util.TimeZone, Calendar.get()GregorianCalendar is a concrete subclass(one which has implementation of all of its inherited members either from interface or abstract class) of a Calendar that implements the most widely used Gregorian Calendar with which we are familiar. java.util.GregorianCalendar vs java.util.
10 min read
Java lang.Long.lowestOneBit() method in Java with Examples
java.lang.Long.lowestOneBit() is a built-in method in Java which first convert the number to Binary, then it looks for first set bit present at the lowest position then it reset rest of the bits and then returns the value. In simple language, if the binary expression of a number contains a minimum of a single set bit, it returns 2^(first set bit po
3 min read
Java Swing | Translucent and shaped Window in Java
Java provides different functions by which we can control the translucency of the window or the frame. To control the opacity of the frame must not be decorated. Opacity of a frame is the measure of the translucency of the frame or component. In Java, we can create shaped windows by two ways first by using the AWTUtilities which is a part of com.su
5 min read
Java lang.Long.numberOfTrailingZeros() method in Java with Examples
java.lang.Long.numberOfTrailingZeros() is a built-in function in Java which returns the number of trailing zero bits to the right of the lowest order set bit. In simple terms, it returns the (position-1) where position refers to the first set bit from the right. If the number does not contain any set bit(in other words, if the number is zero), it r
3 min read
Java lang.Long.numberOfLeadingZeros() method in Java with Examples
java.lang.Long.numberOfLeadingZeros() is a built-in function in Java which returns the number of leading zero bits to the left of the highest order set bit. In simple terms, it returns the (64-position) where position refers to the highest order set bit from the right. If the number does not contain any set bit(in other words, if the number is zero
3 min read
Java lang.Long.highestOneBit() method in Java with Examples
java.lang.Long.highestOneBit() is a built-in method in Java which first convert the number to Binary, then it looks for the first set bit from the left, then it reset rest of the bits and then returns the value. In simple language, if the binary expression of a number contains a minimum of a single set bit, it returns 2^(last set bit position from
3 min read
Java lang.Long.byteValue() method in Java with Examples
java.lang.Long.byteValue() is a built-in function in Java that returns the value of this Long as a byte. Syntax: public byte byteValue() Parameters: The function does not accept any parameter. Return : This method returns the numeric value represented by this object after conversion to byte type. Examples: Input : 12 Output : 12 Input : 1023 Output
3 min read
Java lang.Long.reverse() method in Java with Examples
java.lang.Long.reverse() is a built-in function in Java which returns the value obtained by reversing the order of the bits in the two's complement binary representation of the specified long value. Syntax: public static long reverse(long num) Parameter : num - the number passed Returns : the value obtained by reversing the order of the bits in the
2 min read
java.lang.reflect.Proxy Class in Java
A proxy class is present in java.lang package. A proxy class has certain methods which are used for creating dynamic proxy classes and instances, and all the classes created by those methods act as subclasses for this proxy class. Class declaration: public class Proxy extends Object implements SerializableFields: protected InvocationHandler hIt han
4 min read
Java.math.BigInteger.modInverse() method in Java
Prerequisite : BigInteger Basics The modInverse() method returns modular multiplicative inverse of this, mod m. This method throws an ArithmeticException if m &lt;= 0 or this has no multiplicative inverse mod m (i.e., gcd(this, m) != 1). Syntax: public BigInteger modInverse(BigInteger m) Parameters: m - the modulus. Return Value: This method return
2 min read