BitSet set(int, int) in Java

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

Syntax:

void java.util.BitSet.set(int fromIndex, int toIndex)

This method takes two arguments of type int as its parameters. This method sets the bits from the specified fromIndex (inclusive) to the specified toIndex (exclusive) to true.

Parameters: Two parameters are required for this method.

fromIndex: index of the first bit to be set.

toIndex: index after the last bit to be set.

Throws:

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

Approach 1: When no exception

Java

import java.util.BitSet;

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

        int fromIndex = 2, toIndex = 10;

        bitSet.set(fromIndex, toIndex);
        System.out.println(bitSet);
    }
}

Output:

{2, 3, 4, 5, 6, 7, 8, 9}


Approach 2: IndexOutOfBoundsException 

Java

import java.util.BitSet;

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

        int fromIndex = 12, toIndex = 10;

        bitSet.set(fromIndex, toIndex);
        System.out.println(bitSet);
    }
}

Output:

Exception in thread "main" java.lang.IndexOutOfBoundsException: fromIndex: 12 > toIndex: 10 at java.base/java.util.BitSet.checkRange(BitSet.java:369) at java.base/java.util.BitSet.set(BitSet.java:484)


No comments:

Post a Comment