Academic Java    Java Tutorial  >  Mathematica  >  BitSet

BitSet Example

The BitSet class implements a vector of bits that grows as needed. Each bit has a boolean value of true or false. By default, all bits in the set initially have the value false.

Individual indexed bits can be examined, set, or cleared.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// BitSet example
import java.util.*;

class BitSetExample {

   public static void main(String[] args) {

      BitSet bs = new BitSet(1000);

      boolean b = bs.get(5);

      bs.set(20); bs.set(9); bs.set(769);
      b = bs.get(20);

      bs.clear(20);
      b = bs.get(20);

      bs.flip(20);
      b = bs.get(20);

      BitSet bs2 = bs.get(5,300);
      b = bs2.get(15);

      bs2.set(100);
      int i = bs2.cardinality();

   }
}

8 A new BitSet object is constructed of 1000 bits. All are initially set to 0 i.e. the boolean value false

10 A get() method accesses a bit, which will be false.

12 The indexed bits are set to true by the set() method.

15 The clear() method sets the indexed bit to false.

18 The flip() method toggles the indexed bit value, true to false, or false to true.

21 A new BitSet is created from an existing one. bs2 will contain the bits from bs starting at index 5 and up to but not including index 300.

22 The value of b will be true - it is the value of bit indexed 20 from bs.

25 The cardinality() method returns the number of true bits in the set. 3 is returned, for bits indexed 4 15 100.