THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1
publicBitSet(int size)

Creates a new bit set with enough initial storage to explicitly represent bits
indexed from 0 to size-1. All bits are initially false.

publicBitSet()

Creates a new bit set with a default amount of initial storage. All bits are
initially false.

There are four methods for dealing with individual bits.


public voidset(int index)

Sets the bit specified by index to TRue.

public voidclear(int index)

Sets the bit specified by index to false.

public voidflip(int index)

Sets the bit specified by index to the complement of its current valuetrue
becomes false, and false becomes true.

public booleanget(int index)

Returns the value of the bit specified by index.

A second overloaded form of each of the above methods works on a range of bits. These overloads take a
from index and a to index and either sets, clears, flips, or returns all bits in the range, starting with from
and up to but not including to. For get, the values are returned as a new BitSet. A third overload of
clear takes no arguments and clears the entire set to false. A second variant of the set method takes
both the index (or range) and a boolean value to apply to the bits. This makes it easier for you to change bits
arbitrarily without having to work out whether you need to invoke set or clear.


You can find the index of the next clear or set bit, that is at or after a given index, using the nextClearBit
and nextSetBit methods. If there is no next set bit from that index then 1 is returned.[1]


[1] The only time there can be no next clear bit is if the bit at index Integer.MAX_VALUE
has been setsomething that is extremely unlikely in practice because the bit set could use a
huge amount of memory

Other methods modify the current bit set by applying bitwise logical operations using the bits from another bit
set:


public voidand(BitSet other)

Logically ANDs this bit set with other and changes the value of this set to
the result. The resulting value of a bit in this bit set is TRue only if it was
originally true and the corresponding bit in other is also true.

public voidandNot(BitSet other)
Free download pdf