BitSet nextSetBit(int) in Java

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

Syntax:

int java.util.BitSet.nextSetBit(int fromIndex)

This method takes one argument of type int as its parameter. This method returns the index of the first bit that is set to true that occurs on or after the specified starting index. If no such bit exists then -1 is returned.

Parameters: One parameter is required for this method.

fromIndex: the index to start checking from (inclusive).

Returns: the index of the next set bit, or -1 if there is no such bit.

Throws:

IndexOutOfBoundsException - if the specified index is negative.

Approach 1: When no exception

Java

import java.util.BitSet;

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

        bitSet.set(1);

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

        int fromIndex = 2;
        System.out.println(bitSet.nextSetBit(fromIndex));
    }
}

Output:

5


Approach 2: IndexOutOfBoundsException 

Java

import java.util.BitSet;

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

        bitSet.set(1);

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

        int fromIndex = -1;
        System.out.println(bitSet.nextSetBit(fromIndex));
    }
}

Output:

Exception in thread "main" java.lang.IndexOutOfBoundsException: fromIndex < 0: -1 at java.base/java.util.BitSet.nextSetBit(BitSet.java:715)


No comments:

Post a Comment