Java Utility Library

Java BitSet - get() Method



The java.util.BitSet.get() method returns a new BitSet composed of bits from this BitSet from fromIndex (inclusive) to toIndex (exclusive).

Syntax

public BitSet get(int fromIndex, int toIndex)

Parameters

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

Return Value

Returns a new BitSet from a range of this BitSet.

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.get() method returns a new BitSet composed of bits 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
    for(int i = 0; i <= 20; i+=2)
      BSet.set(i);

    //printing BitSet
    System.out.println("BSet contains: " + BSet);

    //creating a new bitset from the above bitset
    BitSet newBSet = BSet.get(0,10);

    //printing BitSet
    System.out.println("newBSet contains: " + newBSet);
  }
}

The output of the above code will be:

BSet contains: {0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20}
newBSet contains: {0, 2, 4, 6, 8}

❮ Java.util - BitSet