EnumSet in Java is a specialized set implementation for use with enum types. EnumSet was introduced in Java 5 along with the Enum. All of the elements stored in an EnumSet must, explicitly or implicitly, come from a single enum type that is specified while creating the set. All basic operations of the EnumSet execute in constant time. They are likely (though not guaranteed) to be much faster than their HashSet counterparts.
According to Java docs "Enum sets are represented internally as bit vectors. This representation is extremely compact and efficient. The space and time performance of this class should be good enough to allow its use as a high-quality, typesafe alternative to traditional int-based "bit flags." Even bulk operations (such as containsAll and retainAll) should run very quickly if their argument is also an enum set."
How EnumSet works in Java
One of the things to note about EnumSet is that it is an abstract class and uses factory methods to create objects. There are two concrete implementations of EnumSet in Java-
- RegularEnumSet- Private implementation class for EnumSet, for "regular sized" enum types
- JumboEnumSet- Private implementation class for EnumSet, for "jumbo" enum types (i.e., those with more than 64 elements).
Depending upon the size of the Enum any of these classes is instantiated by the EnumSet class itself. If Enum has 64 or fewer enum constants then RegularEnumSet is used otherwise JumboEnumSet.