Java EnumSet

The EnumSet class of the Java collections framework provides a set implementation of elements of a single enum.

There are some key points to remember about EnumSet :

  1. It extends AbstractSet class and implements Set Interface in Java.
  2. EnumSet class is a member of the Java Collections Framework & is not synchronized.
  3. It’s a high-performance set implementation, much faster than HashSet.
  4. 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.
  5. It does not allow null Objects and throws NullPointerException if we do so.It does not allow null Objects and throws NullPointerException if we do so.
  6. It uses a fail-safe iterator, so it won’t throw ConcurrentModificationException if the collection is modified while iterating.

Benefits of using EnumSet
  1. ▪ Due to its implementation using RegularEnumSet and JumboEnumSet, all the methods in an EnumSet are implemented using bitwise arithmetic operations.
  2. ▪ EnumSet is faster than HashSet because we no need to compute any hashCode to find the right bucket.
  3. ▪ The computations are executed in constant time and the space required is very little.
Creating a EnumSet

In order to create an enum set, we must import the java.util.EnumSet package first. four types we can create enumset in java:

  1. ◈ Using allOf(Size)
  2. ◈ Using noneOf(Size)
  3. ◈ Using range(e1, e2) Method
  4. ◈ Using of() Method


                        EnumSet sizes = EnumSet.allOf(Size.class);
                        EnumSet sizes = EnumSet.noneOf(Size.class);
                        EnumSet sizes = EnumSet.range(Size.MEDIUM, Size.EXTRALARGE);
                        EnumSet sizes1 = EnumSet.of(Size.MEDIUM);    
                    
RegularEnumSet

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

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:

  1. ▪ allOf(size)
  2. ▪ noneOf(size)
  3. ▪ range(e1, e2)
  4. ▪ of()

Methods of EnumSet

The EnumSet class provides methods that allow us to perform various elements on the enum set.

Method Name Description
add() inserts the specified element to the EnumSet.
addAll() inserts all the elements of the specified collection to the EnumSet.
remove() removes the specified element from the EnumSet.
removeAll() removes all the elements from the EnumSet.
copyOf() Creates a copy of the EnumSet.
contains() Searches the EnumSet for the specified element and returns a boolean result.
isEmpty() Checks if the EnumSet is empty.
size() Returns the size of the EnumSet.
clear() Removes all the elements from the EnumSet.
Basic Operations on EnumSet

The EnumSet class provides various methods to perform different operations on EnumSet. We will look at some commonly used EnumSet operations.

  1. ▪ Insert Elements to EnumSet
  2. ▪ Access EnumSet Elements
  3. ▪ Remove Elements from EnumSet

Insert Elements to EnumSet

add(), addAll() methods is used to insert elements into EnumSet.


                        import java.util.EnumSet;

                        public class AddEnumSetExample {

                            enum Size {
                                SMALL, MEDIUM, LARGE, EXTRALARGE
                            }

                            public static void main(String[] args) {

                                // Creating an EnumSet using allOf()
                                EnumSet sizes1 = EnumSet.allOf(Size.class);

                                // Creating an EnumSet using noneOf()
                                EnumSet sizes2 = EnumSet.noneOf(Size.class);

                                // Using add method
                                sizes2.add(Size.MEDIUM);
                                System.out.println("EnumSet Using add(): " + sizes2);

                                // Using addAll() method
                                sizes2.addAll(sizes1);
                                System.out.println("EnumSet Using addAll(): " + sizes2);
                            }
                        }

                    
Access EnumSet Elements

To access the elements of a EnumSet, we can use the iterator() method. In order to use this method, we must import the java.util.Iterator package.


                        import java.util.EnumSet;
                        import java.util.Iterator;

                        public class EnumSetAccessExample {

                            enum Size {
                                SMALL, MEDIUM, LARGE, EXTRALARGE
                            }

                            public static void main(String[] args) {

                                // Creating 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(", ");
                                }

                                for(Object s: enumSet) {
                                    System.out.println(s);
                                }
                            }
                        }

                    
Remove Elements

remove(), removeAll() methods are used to remove specified element or all the elements from the EnumSet collection.


                        import java.util.EnumSet;

                        public class RemoveEnumSetExample {

                            enum Size {
                                SMALL, MEDIUM, LARGE, EXTRALARGE
                            }

                            public static void main(String[] args) {

                                // Creating EnumSet using allOf()
                                EnumSet sizes = EnumSet.allOf(Size.class);
                                System.out.println("EnumSet: " + sizes);

                                // Using remove()
                                boolean value1 = sizes.remove(Size.MEDIUM);
                                System.out.println("Is MEDIUM removed? " + value1);

                                // Using removeAll()
                                boolean value2 = sizes.removeAll(sizes);
                                System.out.println("Are all elements removed? " + value2);
                            }
                        }