Java Reference
In-Depth Information
Note
Theconstants'ordinalsandnottheirnamesarestoredinthetreeset,whichis
whythenamesappearunorderedeventhoughtheconstantsarestoredinsortedorder
of their ordinals.
Aswellasbeingmoreawkwardtouse(andverbose)thanthebitset,the
Set
altern-
ativerequiresmorememorytostoreeachconstantandisnotasfast.Becauseofthese
problems,
EnumSet
was introduced.
The
EnumSet
classprovidesa
Set
implementationthatisbasedonabitset.Itsele-
ments are constants that must come from the same enum, which is specified when the
enumsetiscreated.Nullelementsarenotpermitted;anyattempttostoreanullelement
results in a thrown
NullPointerException
.
Listing 5-8.
Creating the
EnumSet
equivalent of
DAYS_OFF
import java.util.EnumSet;
import java.util.Iterator;
import java.util.Set;
enum Weekday
{
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY,
SATURDAY
}
class EnumSetDemo
{
public static void main(String[] args)
{
Set<Weekday> daysOff = EnumSet.of(Weekday.SUNDAY,
Weekday.MONDAY);
Iterator<Weekday> iter = daysOff.iterator();
while (iter.hasNext())
System.out.println(iter.next());
}
}