Java.util.BitSet 类

java.util.BitSet.previousSetBit() 方法返回最近发生的设置为 true 的位的索引在指定的起始索引处或之前。如果不存在这样的位,或者如果给定 -1 作为起始索引,则返回 -1。

语法

public int previousSetBit(int fromIndex)

参数

fromIndex 指定开始检查的索引(含)。

返回值

返回前一个设置位的索引,如果没有这样的位,则返回-1。

异常

抛出IndexOutOfBoundsException ,如果指定的索引小于-1。

示例:

在下面的示例中,java.util.BitSet.previousSetBit() 方法返回设置为 true 且出现在给定 BitSet 中指定起始索引处或之前的最近位的索引。

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //创建一个BitSet
    BitSet BSet = new BitSet();

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

    //打印位集
    System.out.println("BSet contains: " + BSet);

    //查找设置为true的位的索引
    //发生在索引 = 5 或之前
    System.out.print("bit which is set to true on or before index 5 is: ");
    System.out.print(BSet.previousSetBit(5));
  }
}

上述代码的输出将是:

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