Java Reference
In-Depth Information
ThisbitsetisformedbybitwiseinclusiveORingthetraditionalenumeratedtype'sin-
tegerconstantstogetherviathebitwiseinclusiveORoperator(
|
):youcouldalsouse
+
.
Eachconstantmustbeauniquepoweroftwo(startingwithone)becauseotherwiseitis
impossible to distinguish between the members of this bitset.
Todetermineifaconstantbelongstothebitset,createanexpressionthatinvolvesthe
bitwise AND operator (&). For example,
((DAYS_OFF&MONDAY) == MONDAY)
bitwiseANDs
DAYS_OFF
(3)with
MONDAY
(2),whichresultsin2.Thisvalueiscom-
pared via
==
with
MONDAY
(2), and the result of the expression is true:
MONDAY
is a
member of the
DAYS_OFF
bitset.
Youcanaccomplishthesametaskwithanenumbyinstantiatinganappropriate
Set
implementation class and calling the
add()
method multiple times to store the con-
stants in the set.
Listing 5-7
illustrates this more awkward alternative.
Listing 5-7.
Creating the
Set
equivalent of
DAYS_OFF
import java.util.Set;
import java.util.TreeSet;
enum Weekday
{
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY,
SATURDAY
}
class DaysOff
{
public static void main(String[] args)
{
Set<Weekday> daysOff = new TreeSet<>();
daysOff.add(Weekday.SUNDAY);
daysOff.add(Weekday.MONDAY);
System.out.println(daysOff);
}
}
When you run this application, it generates the following output:
[SUNDAY, MONDAY]