Java EnumSet
In Java, an EnumSet is a specialized set collection that is designed to work with Java Enum types. EnumSet is a highly efficient implementation of the Set interface for Enum types, providing constant-time performance for the basic operations (add, remove, contains, etc.), and supporting all of the Set operations such as union, intersection, difference, and symmetric difference.
The EnumSet class is a part of the java.util package and provides many useful methods for working with sets of Enum types.
Here is an example of how to use an EnumSet in Java:
refer to:theitroad.comimport java.util.EnumSet; public class EnumSetExample { // Define an enum type enum Color { RED, GREEN, BLUE } public static void main(String[] args) { // Creating an EnumSet EnumSet<Color> set = EnumSet.of(Color.RED, Color.BLUE); // Adding elements to the EnumSet set.add(Color.GREEN); // Printing the EnumSet System.out.println("EnumSet: " + set); // Removing an element from the EnumSet set.remove(Color.RED); // Printing the EnumSet after removing an element System.out.println("EnumSet after removing an element: " + set); // Checking if an element is present in the EnumSet boolean isPresent = set.contains(Color.GREEN); System.out.println("Is GREEN present in the EnumSet? " + isPresent); // Checking the size of the EnumSet int size = set.size(); System.out.println("Size of the EnumSet: " + size); // Clearing the EnumSet set.clear(); System.out.println("EnumSet after clearing: " + set); } }
Output:
EnumSet: [RED, BLUE, GREEN] EnumSet after removing an element: [BLUE, GREEN] Is GREEN present in the EnumSet? true Size of the EnumSet: 2 EnumSet after clearing: []
In the example above, we have defined an enum type Color
and created an EnumSet of the Color
enum. We have added elements to the EnumSet, removed an element, checked if an element is present, checked the size of the EnumSet, and cleared the EnumSet.