What is an enumSet in Java?

An enumSet is a specialized type of class which implements the Set interface needed to use the enum type.

Features of enumSet

  • An enumSetextends AbstractSet and implements SetInterface.

  • An enumSet is a Java Collections member, it is not synchronized.

  • An enumSet is a high performing set implementation that works faster than the HashSet.

  • All the elements in an enumSet must be of a single enumeration type that is specified when the set is created.

The following illustration explains the enumSet link with other interfaces, collections, and sets.

svg viewer

Why enumSet

All the methods in an enumSet are implemented using bitwise arithmetic operations. These computations are very fast and, therefore, all the basic operations are executed in constant time. These computations ​use less memory and are compact and efficient.

Methods in enumSet class

Method Description
allOf (Class elementType) This method is used to create an enum set containing all of the elements with a specified element type.
noneOf (Class elementType) This method is used to create an empty enum set with the specified element type.
copyOf (Collection c) This method is used to create an enum set that is initialized from the specified collection.
of (E e) This method is used to create an enum set initially, containing a single specified element.
range (E from, E to) This method is used to initially create an enum set that contains the range of specified elements.
clone() This method is used to return a copy of the specific set.

Code

​The code below creates an enumSet and then calls a few methods:

import java.util.EnumSet;
enum example
{
one, two, three, four, five
};
public class main
{
public static void main(String[] args)
{
// Creating a set
EnumSet<example> set1, set2, set3, set4;
// Adding elements
set1 = EnumSet.of(example.four, example.three,
example.two, example.one);
set2 = EnumSet.complementOf(set1);
set3 = EnumSet.allOf(example.class);
set4 = EnumSet.range(example.one, example.three);
System.out.println("Set 1: " + set1);
System.out.println("Set 2: " + set2);
System.out.println("Set 3: " + set3);
System.out.println("Set 4: " + set4);
}
}
Copyright ©2024 Educative, Inc. All rights reserved