Java Reference
In-Depth Information
In this class, the attributes are assigned increasing values beginning with 0 . You can use
these values to get and set the appropriate bits in a set. First, you need to create a BitSet
object:
BitSet connex = new BitSet();
This constructor creates a set with no specified size. You also can create a set with a spe-
cific size:
BitSet connex = new BitSet(4);
This creates a set containing four Boolean bits. Regardless of the constructor used, all
bits in new sets are initially set to false . After you have a set, you can set and clear the
bits by using set( int ) and clear( int ) methods with the bit constants you defined:
connex.set(ChannelAttributes.WRITABLE);
connex.set(ChannelAttributes.STREAMABLE);
connex.set(ChannelAttributes.FLEXIBLE);
connex.clear(ChannelAttributes.WRITABLE);
In this code, the WRITABLE , STREAMABLE , and FLEXIBLE attributes are set and then the
WRITABLE bit is cleared. The class name is used for each attribute because the constants
are class variables in the ChannelAttributes class.
You can get the value of individual bits in a set by using the get() method:
boolean isWriteable = connex.get(ChannelAttributes.WRITABLE);
You can find out how many bits are being represented by a set with the size method:
int numBits = connex.size();
The BitSet class also provides other methods for performing comparisons and bitwise
operations on sets such as AND , OR , and XOR . All these methods take a BitSet object as
their only argument.
Today's first project is HolidaySked , a Java class that uses a set to keep track of which
days in a year are holidays.
A set is employed because HolidaySked must be able to take any day of the year and
answer the same yes/no question: Are you a holiday?
Enter the text of Listing 8.1 into your editor and save the file as HolidaySked.java .
Search WWH ::




Custom Search