English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java flow control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List (list)

Java Queue (queue)

Java Map collection

Java Set collection

Java Input/Output (I/O)/O)

Java Reader/Writer

Java other topics

Java EnumSet

In this tutorial, we will learn about the Java EnumSet class and its various methods through examples.

The Java collection framework's EnumSet class provides a collection implementation for a single enumeration element.

Before learning EnumSet, please make sure you understandJava Enums.

It implementsSet interface.

Create EnumSet

To create an enumeration set, we must first import the java.util.EnumSet package.

Unlike other collection implementations, enumeration sets do not have a public constructor. We must use predefined methods to create an enumeration set.

1.Use allOf(Size)

The allOf() method creates an enumeration set containing all values of the specified enumeration type Size. For example,

import java.util.EnumSet;
class Main {
    //An enumeration named Size
    enum Size {
        SMALL, MEDIUM, LARGE, EXTRALARGE
    }
    
    public static void main(String[] args) {
        //Create an EnumSet using allOf()
        EnumSet<Size> sizes = EnumSet.allOf(Size.class);
        System.out.println("EnumSet: ") + sizes);
    }
}

Output result

EnumSet: [SMALL, MEDIUM, LARGE, EXTRALARGE]

Note declaration

EnumSet<Size> sizes = EnumSet.allOf(Size.class);

Here, Size.class represents the Size enumeration we created.

2.Use noneOf(Size)

The noneOf() method creates an empty enumeration set. For example,

import java.util.EnumSet;
class Main {
     //An enumeration named Size
    enum Size {
        SMALL, MEDIUM, LARGE, EXTRALARGE
    }
    public static void main(String[] args) {
        // Create an EnumSet using noneOf()
        EnumSet<Size> sizes = EnumSet.noneOf(Size.class);
        System.out.println("Empty EnumSet: " + sizes);
    }
}

Output result

Empty EnumSet: []

Here, we created an empty enumeration named sizes.

Note:We can only insert elements of enumeration type Size in the above program. This is because we created an empty enumeration set using Size enumeration.

3.Use range(e1,e2method

The range() method creates an enumeration set containing e1and e2All enumeration values between, including these two. For example

import java.util.EnumSet;
class Main {
    enum Size {
        SMALL, MEDIUM, LARGE, EXTRALARGE
    }
    public static void main(String[] args) {
        //Create an EnumSet using range()
        EnumSet<Size> sizes = EnumSet.range(Size.MEDIUM, Size.EXTRALARGE);
        System.out.println("EnumSet: ") + sizes);
    }
}

Output result

EnumSet: [MEDIUM, LARGE, EXTRALARGE]

4.use of() method

The of() method creates an EnumSet containing specified elements. For example,

import java.util.EnumSet;
class Main {
    enum Size {
        SMALL, MEDIUM, LARGE, EXTRALARGE
    }
    public static void main(String[] args) {
        //Use of() with a single parameter
        EnumSet<Size> sizes1 = EnumSet.of(Size.MEDIUM);
        System.out.println("EnumSet1: " + sizes1);
        EnumSet<Size> sizes2 = EnumSet.of(Size.SMALL, Size.LARGE);
        System.out.println("EnumSet2: " + sizes2);
    }
}

Output result

EnumSet1: [MEDIUM]
EnumSet2: [SMALL, LARGE]

EnumSet methods

The EnumSet class provides some methods that allow us to perform various operations on EnumSets.

Insert elements into EnumSet

  • add() - Insert the specified enum value into the EnumSet

  • addAll() - Insert all elements of the specified collection into the collection

For example,

import java.util.EnumSet;
class Main {
    enum Size {
        SMALL, MEDIUM, LARGE, EXTRALARGE
    }
    public static void main(String[] args) {
        //Create an EnumSet using allOf()
        EnumSet<Size> sizes1 = EnumSet.allOf(Size.class);
        //Create an EnumSet using noneOf()
        EnumSet<Size> sizes2 = EnumSet.noneOf(Size.class);
        //Add elements using add method
        sizes2.add(Size.MEDIUM);
        System.out.println("EnumSet using add() method: ") + sizes2);
        //Using addAll() method
        sizes2.addAll(sizes1);
        System.out.println("EnumSet using addAll() method: ") + sizes2);
    }
}

Output result

EnumSet using add() method: [MEDIUM]
EnumSet using addAll() method: [SMALL, MEDIUM, LARGE, EXTRALARGE]

In the above example, we used the addAll() method to add sizes1All elements of the EnumSet are inserted into sizes2EnumSet.

We can also use addAll() to insert elements from other collections (such as ArrayList, LinkedList, etc.) into the EnumSet. However, all collections should have the same enum type.

Access EnumSet elements

To access the elements of an EnumSet, we can use the iterator() method. To use this method, we must import the java.util.Iterator package. For example,

import java.util.EnumSet;
import java.util.Iterator;
class Main {
    enum Size {
        SMALL, MEDIUM, LARGE, EXTRALARGE
    }
    public static void main(String[] args) {
        //Create an EnumSet using allOf()
        EnumSet<Size> sizes = EnumSet.allOf(Size.class);
        Iterator<Size> iterate = sizes.iterator();
        System.out.print("EnumSet: ");
        while(iterate.hasNext()) {
            System.out.print(iterate.next());
            System.out.print(", ");
        }
    }
}

Output result

EnumSet: SMALL, MEDIUM, LARGE, EXTRALARGE,

Precautions:

  • hasNext() - If there is a next element in the enum set, return true

  • next()  - Return the next element in the enum set

Remove EnumSet elements

  • remove() - Remove the specified element from the enum set

  • removeAll() - Remove all elements from the enum set

For example,

import java.util.EnumSet;
class Main {
    enum Size {
        SMALL, MEDIUM, LARGE, EXTRALARGE
    }
    public static void main(String[] args) {
        //Use allOf() to create EnumSet
        EnumSet<Size> sizes = EnumSet.allOf(Size.class);
        System.out.println("EnumSet: ") + sizes);
        // Use remove()
        boolean value1 = sizes.remove(Size.MEDIUM);
        System.out.println("Has MEDIUM been deleted? ") + value1);
        // Use removeAll()
        boolean value2 = sizes.removeAll(sizes);
        System.out.println("Are all elements removed? ") + value2);
    }
}

Output result

EnumSet: [SMALL, MEDIUM, LARGE, EXTRALARGE]
Has MEDIUM been deleted? true
Are all elements removed? true

Other methods

MethodDescription
copyOf()Create a copy of EnumSet
contains()Search for the element specified by EnumSet in the middle and return a boolean result
isEmpty()Check if the EnumSet is empty
size()Return the size of EnumSet
clear()Remove all elements from EnumSet

Interfaces for Cloneable and Serializable

The EnumSet class also implements the Cloneable and Serializable interfaces.

Cloneable Interface (Cloneable)

It allows the EnumSet class to create a copy of the instance of the class.

Serializable Interface (Serializable)

Every time you need to transmit a Java object over the network, you need to convert the object into bits or bytes. This is because Java objects cannot be transmitted over the network.

The Serializable interface allows a class to be serialized. This means that Serializable can convert the object of the class implemented into bits or bytes.

Why choose EnumSet?

Enum sets provide a more efficient way to store enum values than other set implementations (such as HashSet, TreeSet).

Enum sets store only the enum values of specific enums. Therefore, the JVM already knows all possible values of the collection.

That's why enum sets are internally implemented as bit sequences. Bit specifies whether an element appears in the enum set.

If the element exists in the collection, open the corresponding bit.