Java Utility Library

Java BitSet - previousSetBit() Method



The java.util.BitSet.previousSetBit() method returns the index of the nearest bit that is set to true that occurs on or before the specified starting index. If no such bit exists, or if -1 is given as the starting index, then -1 is returned.

Syntax

public int previousSetBit(int fromIndex)

Parameters

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

Return Value

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

Exception

Throws IndexOutOfBoundsException, if the specified index is less than -1.

Example:

In the example below, the java.util.BitSet.previousSetBit() method returns the index of the nearest bit that is set to true and occurs on or before the specified starting index in the given BitSet.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a BitSet
    BitSet BSet = new BitSet();

    //populating BitSet
    BSet.set(1);
    BSet.set(2);
    BSet.set(8);
    BSet.set(9);
    BSet.set(10); 

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

    //finding index of the bit which is set to true
    //which occurs on or before index = 5
    System.out.print("bit which is set to true on or before index 5 is: ");
    System.out.print(BSet.previousSetBit(5));
  }
}

The output of the above code will be:

BSet contains: {1, 2, 8, 9, 10}
bit which is set to true on or before index 5 is: 2

❮ Java.util - BitSet