Java Utility Library

Java BitSet - clear() Method



The java.util.BitSet.clear() method is used to set the bits from the specified fromIndex (inclusive) to the specified toIndex (exclusive) to false.

Syntax

public void clear(int fromIndex, int toIndex)

Parameters

fromIndex Specify the index of the first bit to be cleared.
toIndex Specify the index after the last bit to be cleared.

Return Value

void type.

Exception

Throws IndexOutOfBoundsException, if fromIndex is negative, or toIndex is negative, or fromIndex is larger than toIndex.

Example:

In the example below, the java.util.BitSet.clear() method is used to clear the bit specified by the given range from the given BitSet.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a BitSet
    BitSet BSet = new BitSet();

    //populating BitSet
    BSet.set(10);
    BSet.set(20);
    BSet.set(30);
    BSet.set(40);
    BSet.set(50);

    //printing BitSet
    System.out.println("Before applying clear() method.");
    System.out.println("BSet contains: " + BSet);

    //using clear method to clear index 20 to index 50
    BSet.clear(20, 50);

    //printing BitSet
    System.out.println("\nAfter applying clear() method."); 
    System.out.println("BSet contains: " + BSet);   
  }
}

The output of the above code will be:

Before applying clear() method.
BSet contains: {10, 20, 30, 40, 50}

After applying clear() method.
BSet contains: {10, 50}

❮ Java.util - BitSet