What is the BitSet.size() method in Java?
Overview
In Java, size() is a BitSet instance method that returns the total bit space that the BitSet object is currently using to represent bit values.
The BitSet class is defined in the java.util package. To import the BitSet class, we use the following statement.
import java.util.BitSet;
Syntax
public int size()
Parameters
This method has no parameters.
Return value
This method returns the number of bits currently in this bit set.
Example
import java.util.Arrays;import java.util.BitSet;public class Main{public static void main(String[] args) {// Create empty BitSet objectBitSet bitSet = new BitSet();// Set the bit at index 2bitSet.set(2);// Set the bit at index 143bitSet.set(143);// Get the size of the Bitset object using the size()System.out.printf("%s.size() = %s" , bitSet, bitSet.size());}}
Explanation
- Lines 1–2: We import the relevant packages.
- Line 8: We create an empty
BitSetobjectbitSet. - Line 11: We set the bit at index 2.
- Line 14: We set the bit at index 143.
- Line 17: We print the size of the
BitSetobject defined in line 8 using thesize()method.
By default, the size of the BitSet is 64 starting from 0 to 63. This means if we replace 143 with a value <=63 at line 14, we’ll get 64 because both bits lie in the same slot. However, setting it to 64 will result in 128. It means that the bit size is calculated in multiple of 64-bit slot, and it remains the same for the next 64 bits.