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. This is a legacy class but it has been completely re-engineered in Java 2, version 1.4.
BitSet class Constructors
- BitSet()
- BitSet(int no_Of_Bits)
Important Points :
- The size of the array is flexible and can grow to accommodate additional bit as needed.
- As it is an array, the index is zero-based and the bit values can be accessed only by non-negative integers as an index .
- The default value of the BitSet is boolean false with a representation as 0 (off).
- Calling the clear method makes the bit values set to false.
- BitSet uses about 1 bit per boolean value.
- To access a specific value in the BitSet, the get method is used with an integer argument as an index.
Syntax:
To create a new bitset
// Constructors of BitSet class
BitSet bs1 = new BitSet();
/* set is BitSet class method expalined in below part */
// assigning values to bitset 1
bs1.set(0);
bs1.set(1);
Important Methods in BitSet Class:
- set() : java.util.BitSet.set() method is a sets the bit at the specified index to the specified value
- clone() : java.util.BitSet.clone() method clones a BitSet produces a new BitSet that is equal to it. The clone of the bit set is another bit set that has exactly the same bits set to true as this bit set.
- cardinality() : java.util.BitSet.cardinality() method is used to find the no. of elements in Bitset
- xor() : java.util.BitSet.xor() method performs the logical Xor operation on the bitsets.
This bit set is modified so that a bit in it has the value true if and only if :
- The bit initially has the value true, and the corresponding bit in the argument has the value false.
- The bit initially has the value false, and the corresponding bit in the argument has the value true.
To read more about BitSets Click here
Try the following example in the editor below.
You are given two bitset b1 and b2, perform the operations defined in the comments in the editor below.