Introduction
There are a variety of applications that can be built using Java, one of the most popular programming languages. Enumerations are often used in applications to serve a group of named constants. The EnumSet interface can be used if you want to implement the Set interface with an enumeration type in Java. The focus of this article will be on EnumSet.
What is EnumSet?
This class extracts AbstractSet and implements the Set interface. EnumSet overrides many of the methods of AbstractSet and AbstractCollection, even though AbstractSet and AbstractCollection implement the Set and Collection interfaces. The benefit of EnumSet over HashSet is that all methods are implemented using bitwise arithmetic operations; hence it is very fast. EnumSet is very fast since all its basic operations can be performed within a constant amount of time. Bit vectors are used internally to represent enum sets.
Compared with other set implementations (such as HashSet and TreeSet), EnumSet is more efficient at storing enum values. In enum sets, only values for one enum are stored. As a result, the JVM knows all possible values for the set.
Implementation of EnumSet
Many static factory methods are associated with the enumSet class that can be used to create instances. The JDK provides two different implementations:
-
RegularEnumSet: It represents the bit vector as a single long. The long element consists of a single bit for each enum value. It is pretty easy to tell whether a value is present because the i-th bit will store the value of the enum. This implementation helps to store up to 64 elements since long is a 64-bit data type.
-
JumboEnumSet: This bit vector uses an array of long elements. It has a maximum number of 64 elements. The array index where the value is stored is calculated slightly differently than that for the RegularEnumSet.
According to the number of elements in an enum, the factory methods of EnumSet generate instances of one implementation or another.
if (a.length <= 64)
return new RegularEnumSet<>(element_type, a);
else
return new JumboEnumSet<>(element_type, a);