BitSet get(int, int) in Java

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

Syntax:

BitSet java.util.BitSet.get(int fromIndex, int toIndex)

This method takes two arguments of type int as its parameters. This method returns a new BitSet composed of bits from this BitSetfrom fromIndex (inclusive) to toIndex (exclusive).

Parameters: Two parameters are required for this method.

fromIndex: index of the first bit to include.

toIndex: index after the last bit to include.

Returns: a new BitSet from a range of this BitSet.

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 BitSetget2 {
    public static void main(String[] args) {
        BitSet bitSet = new BitSet(4);

        bitSet.set(1);

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

        int fromIndex = 1, toIndex = 8;
        System.out.println(bitSet.get(fromIndex, toIndex));
    }
}

Output:

{0, 4, 5}


Approach 2: IndexOutOfBoundsException

Java

import java.util.BitSet;

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

        bitSet.set(1);

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

        int fromIndex = 6, toIndex = 5;
        System.out.println(bitSet.get(fromIndex, toIndex));
    }
}

Output:

Exception in thread "main" java.lang.IndexOutOfBoundsException: fromIndex: 6 > toIndex: 5 at java.base/java.util.BitSet.checkRange(BitSet.java:369) at java.base/java.util.BitSet.get(BitSet.java:648)


No comments:

Post a Comment