I have the following example:
import java.util.EnumSet;
import java.util.Iterator;
public class SizeSet {
public static void main(String[] args) {
From Joshua Bloch's book itself and in his own word:
The java.util package provides EnumSet class to efficiently represent sets of values drawn from a single enum type. This class implements the Set interface, providing all of the richness, type safety and interoperability you get with any other Set implementation. But internally, each EnumSet is represented as a bit vector. If the underlying enum type has sixty-four or fewer elements -- and most do -- the entire EnumSet is represented with a single long, so its performance is comparable to that of a bit field. Bulk operations, such as removeAll and retainAll, are implemented using bit wise arithmetic, just as you'll do manually for bit fields. But you are insulated from the ugliness and error-proneness of manual bit twiddling. The EnumSet does the hard work for you.
So we can do something like this.
public class SizeSet {
public enum Size {S, M, L, XL, XXL, XXXL}
public void applySize(Set<Size> sizes){}
}
Client Code calling it might do something like
SizeSet largeSizeSet = new SizeSet();
largeSizeSet.applySize(EnumSet.of(Size.L, Size.XXL, Size.XXL));
Note that the applySize method takes the Set<Size>
rather than an EnumSet<Size>
. While it is pretty
obvious and likely that the client would pass an EnumSet to the method, it is a good practice to accept an interface rather than the concrete implementation.
An EnumSet
is a specialized Set collection to work with enum classes. It implements the Set
interface and extends from AbstractSet
:
When you plan to use an EnumSet youhave to take into consideration some points:
Now, the EnumSet largeSize
part is a variable declaration so yes, it's of type EnumSet. Please notice that you can add the type of elements in the collection for better type safety: EnumSet<Size>
Check out this article to learn more about EnumSet.
According to Oracle doc
Enum sets are represented internally as bit vectors. This representation is extremely compact and efficient.
Readable, type safe, low memory footprint... What do you want more?
It quickly turn any Enum elements into a set, EnumSet is yet another type of Set.
public enum Style { BOLD, ITALIC, UNDERLINE, STRIKETHROUGH }
EnumSet.of(Style.BOLD, Style.ITALIC);