Steffan Harris Steffan Harris - 2 months ago 27
Java Question

Java BitSet Example

I'm looking for a good Java

BitSet
example to work with 0 and 1s. I tried looking at the Javadocs but I don't understand the usage of the class by just reading that. For instance, how would the
and
,
or
, and
xor
methods work on two different
BitSet
objects?

For example:

BitSet bits1 = new BitSet();
BitSet bits2 = new BitSet();

bits2.set(1000001);
bits1.set(1111111);

bits2.and(bits1);

System.out.println(bits2);


If I do this it returns
bits2
as empty why is that?

Answer

For the specific problem you mentioned: when you called bits2.set(1000001), you set the one millionth and first bit to true. Then when you intersected with bits1, which had the one million, 111 thousand, and 111st bit set, they had no bits in common.

I think what you meant to do was

 bits2.set(0); // set the 0th bit
 bits2.set(6); // set the 6th bit

Does this help clear things up?