BitSet clear(int) in Java

clear(int): This method is available in java.util.BitSet class of Java.

Syntax:

void java.util.BitSet.clear(int bitIndex)

This method takes one argument of type int as its parameter. This method sets the bit specified by the index to false.

Parameters: One parameter is required for this method.

bitIndex: the index of the bit to be cleared.

Throws:

IndexOutOfBoundsException - if the specified index is negative.

Approach 1: When no exceptions

Java 

import java.util.BitSet;

public class BitSetclear2 {
    public static void main(String[] args) {
        BitSet bitSet = new BitSet(20);

        bitSet.set(1);

        bitSet.set(5);
        bitSet.set(6);
        bitSet.set(10);

        int bitIndex = 2;
        bitSet.clear(bitIndex);
        System.out.println(bitSet);
    }
}

Output:

{1, 5, 6, 10}


Approach 2: IndexOutOfBoundsException 

Java

import java.util.BitSet;

public class BitSetclear2 {
    public static void main(String[] args) {
        BitSet bitSet = new BitSet(20);

        bitSet.set(1);

        bitSet.set(5);
        bitSet.set(6);
        bitSet.set(10);

        int bitIndex = -1;
        bitSet.clear(bitIndex);
        System.out.println(bitSet);
    }
}

Output:

Exception in thread "main" java.lang.IndexOutOfBoundsException: bitIndex < 0: -1 at java.base/java.util.BitSet.clear(BitSet.java:543)


No comments:

Post a Comment