Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java BitSet Example

Tags:

java

bitset

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?

like image 500
Steffan Harris Avatar asked Feb 17 '12 18:02

Steffan Harris


People also ask

What is BitSet used for Java?

BitSet is a class defined in the java. util package. It creates an array of bits represented by boolean values.

Is there BitSet in Java?

The BitSet class creates a special type of array that holds bit values. The BitSet array can increase in size as needed. This makes it similar to a vector of bits.

Why do we use BitSet?

A BitSet is a very efficient for a set of non-negative integers within a (not too large) range. Much more efficient than arrays and hash maps. An EnumSet is implemented the same way as a BitSet .

What is the difference between a regular array and a BitSet in Java?

The difference between a boolean array and a BitSet is essentially the same as the difference between an array of object references and a List.


1 Answers

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?

like image 110
Louis Wasserman Avatar answered Sep 19 '22 17:09

Louis Wasserman