Java Reference
In-Depth Information
The EnumSet<E> collection class enables you to store one or more enumeration constants of a given type, E .
A primary use for this collection class is as you saw in the context of file I/O. It provides a convenient way
of packaging an arbitrary number of enumeration constants so they can be passed to a method as a single
argument. There are no constructors for this class. You create an EnumSet<E> object by using one of the
static factory methods that the class defines.
NOTE A factory method is a static method that is not a constructor, but nonetheless creates
objects. A factory method can provide advantages over a constructor in some situations. For
example,itmakesitpossibletolimitthenumberofobjectsthatmaybecreated.Itallowscach-
ing of objects so objects may be reused. It also allows a reference to be returned that is an
interface type that the object implements. You saw this with static methods in the Files class.
The static of() method in the EnumSet<E> generic class is the factory method that you have already used,
and the one you are likely to use most often. It comes in six overloaded versions. Five accept one, two, three,
four, or five arguments of type E to be stored in the collection. The sixth method uses a varargs parameter
list to permit an arbitrary number of arguments of type E . The reason for implementing the of() method as
a set of overloads like this is to maximize efficiency when you put a small number of enumeration constants
in a set. The varargs parameter list slows things down, and the overloads for one to five arguments ensure
that performance is excellent in the majority of situations.
Assuming you have a static import statement for the constants from the StandardOpenOption enumera-
tion, you could define an EnumSet<> object like this:
EnumSet<StandardOpenOption> set = EnumSet.of(CREATE,WRITE);
The more common usage is to create an EnumSet<> object in the argument expression, like this:
WritableByteChannel fileOut = Files.newByteChannel(
file, EnumSet.of(WRITE, CREATE, TRUNCATE_EXISTING));
You have seen this usage several times before in Chapter 10.
After you have the EnumSet<StandardOpenOption> object, set , you can create another EnumSet<> ob-
ject that represents the set of constants that are not in set :
EnumSet<StandardOpenOption> setComplement = EnumSet.complementOf(set);
setComplement contains all the constants from the StandardOpenOption enumeration that are not in
set .
You might want to create an empty set that can hold enumeration constants of a given type:
EnumSet<StandardOpenOption> options = EnumSet.noneOf(StandardOpenOption.class);
The static noneOf() method creates an empty set that can hold constants of the type you specify as the
argument. The expression StandardOpenOption.class specifies the class type for the StandardOpenOp-
tion enumeration. You can test for an empty set by calling the isEmpty() method for the object.
Search WWH ::




Custom Search