• Java Data Structures Tutorial

Printing the elements of the BitSet



The get() method of the BitSet class returns the current state/value of the bit at the specified index. Using this You can print the contents of the BitSet.

Example

import java.util.BitSet;
public class PrintingElements {
   public static void main(String args[]) {
      BitSet bitSet = new BitSet(10);  
      
      for (int i = 1; i<25; i++) {
         if(i%2==0) {
            bitSet.set(i);
         }      
      }
      System.out.println("After clearing the contents ::");
      
      for (int i = 1; i<=25; i++) {
         System.out.println(i+": "+bitSet.get(i));       
      }
   }
}

Output

After clearing the contents ::
1: false
2: true
3: false
4: true
5: false
6: true
7: false
8: true
9: false
10: true
11: false
12: true
13: false
14: true
15: false
16: true
17: false
18: true
19: false
20: true
21: false
22: true
23: false
24: true
25: false

Or, you can directly print the contents of the bit set using the println() method.

System.out.println(bitSet);
Advertisements