Java BitSet previousSetBit()方法

来源:这里教程网 时间:2026-02-17 20:34:50 作者:

Java BitSet previousSetBit()方法

BitSet是一个定义在java.util包中的类。它创建了一个由布尔值表示的比特数组。

Bitset.previousSetBit()

该方法用于查找在指定的起始索引上或之前是否有任何真实的位出现。

该函数返回在指定的起始索引上或之前出现的最近的被设置为真实的位的索引。如果没有这样的位,或者如果给了-1作为起始索引,那么就会返回-1。

语法。

public int previousSetBit(int fromIndex)

参数。这个方法需要一个强制性的参数fromIndex,它是在这个fromIndex上或之前发生的真位的开始检查的索引(包括)。

返回值。该方法返回发生在指定索引上或之前的前一个设定位的索引,如果没有这样的位,则返回-1。

异常情况。如果指定的索引小于-1,此方法会抛出IndexOutOfBoundsException。

注意:要遍历BitSet中的真实位,请使用下面的循环。

for (int i = bs.length(); (i = bs.previousSetBit(i-1)) >= 0; ) {     // operate on index i here }

下面的程序说明了previousSetBit()方法。

例1:展示previousSetBit()函数的实现。

// Java program illustrating Bitset// previousSetBit() function.  import java.util.*;public class GFG {    public static void main(String[] args)    {        // Constructors of BitSet class        BitSet bs1 = new BitSet();        BitSet bs2 = new BitSet();        BitSet bs3 = new BitSet();          /* assigning values to set1*/        bs1.set(0);        bs1.set(1);        bs1.set(2);        bs1.set(4);          // assign values to bs2        bs2.set(4);        bs2.set(6);        bs2.set(5);        bs2.set(1);        bs2.set(2);        bs2.set(3);        bs2.set(12);          // Printing the 2 Bitsets        System.out.println("bs1 : " + bs1);        System.out.println("bs2 : " + bs2);        System.out.println("bs3 : " + bs3);          // Performing length() on bitsets        System.out.println("Previous Set Bit of bs1 "                           + bs1.previousSetBit(2));        System.out.println("Previous Set Bit of bs2 "                           + bs2.previousSetBit(1));        System.out.println("Previous Set Bit of bs3 "                           + bs3.previousSetBit(3));    }}

输出:

bs1 : {0, 1, 2, 4}bs2 : {1, 2, 3, 4, 5, 6, 12}bs3 : {}Previous Set Bit of bs1 2Previous Set Bit of bs2 1Previous Set Bit of bs3 -1

例2:显示IndexOutOfBoundException。

// Java program illustrating Bitset// previousSetBit() function.  import java.util.*;public class GFG {    public static void main(String[] args)    {        // Constructors of BitSet class        BitSet bs1 = new BitSet();          // assigning values to set1        bs1.set(0);        bs1.set(1);        bs1.set(2);        bs1.set(4);          // Printing the Bitset        System.out.println("bs1 : " + bs1);          try {            // Passing -2 as parameter            System.out.println(bs1.previousSetBit(-2));        }        catch (Exception e) {            System.out.println("Exception when "                               + "index less than -1 is passed "                               + "as parameter : " + e);        }    }}

输出:

bs1 : {0, 1, 2, 4}Exception when index less than -1 is passed as parameter : java.lang.IndexOutOfBoundsException: fromIndex < -1: -2

相关推荐