Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

458 Part II: The Java Library


The EnumSet Class


EnumSetextendsAbstractSetand implementsSet. It is specifically for use with keys of an
enumtype. It is a generic class that has this declaration:

class EnumSet<E extends Enum<E>>

Here,Especifies the elements. Notice thatEmust extendEnum<E>, which enforces the
requirement that the elements must be of the specifiedenumtype.
EnumSetdefines no constructors. Instead, it uses the factory methods shown in Table 17-7
to create objects. All methods can throwNullPointerException. ThecopyOf( )andrange( )
methods can also throwIllegalArgumentException. Notice that theof( )method is overloaded
a number of times. This is in the interest of efficiency. Passing a known number of arguments
can be faster than using avarargparameter when the number of arguments is small.

Accessing a Collection via an Iterator


Often, you will want to cycle through the elements in a collection. For example, you might
want to display each element. One way to do this is to employ aniterator,which is an object
that implements either theIteratoror theListIteratorinterface.Iteratorenables you to cycle
through a collection, obtaining or removing elements.ListIteratorextendsIteratorto allow

Method Description
static <E extends Enum<E>>
EnumSet<E> allOf(Class<E>t)

Creates anEnumSetthat contains the elements in the
enumeration specified byt.
static <E extends Enum<E>> EnumSet<E>
complementOf(EnumSet<E>e)

Creates anEnumSetthat is comprised of those elements not
stored ine.
static <E extends Enum<E>>
EnumSet<E> copyOf(EnumSet<E>c)

Creates anEnumSetfrom the elements stored inc.

static <E extends Enum<E>>
EnumSet<E> copyOf(Collection<E>c)

Creates anEnumSetfrom the elements stored inc.

static <E extends Enum<E>>
EnumSet<E> noneOf(Class<E>t)

Creates anEnumSetthat contains the elements that are not in
the enumeration specified byt,which is an empty set by definition.
static <E extends Enum<E>>
EnumSet<E> of(Ev, E ...varargs)

Creates anEnumSetthat containsvand zero or more
additional enumeration values.
static <E extends Enum<E>>
EnumSet<E> of(Ev)

Creates anEnumSetthat containsv.

static <E extends Enum<E>>
EnumSet<E> of(Ev1, Ev2)

Creates anEnumSetthat containsv1andv2.

static <E extends Enum<E>>
EnumSet<E> of(Ev1, Ev2, Ev3)

Creates anEnumSetthat containsv1throughv3.

static <E extends Enum<E>>
EnumSet<E> of(Ev1, Ev2, Ev3, Ev4)

Creates anEnumSetthat containsv1throughv4.

static <E extends Enum<E>>
EnumSet<E> of(Ev1, Ev2, Ev3, Ev4,
Ev5)

Creates anEnumSetthat containsv1throughv5.

static <E extends Enum<E>>
EnumSet<E> range(Estar t, Eend)

Creates anEnumSetthat contains the elements in the range
specified bystar tandend.

TABLE 17-7 The Methods Defined byEnumSet
Free download pdf