Java BitSet previousClearBit()方法

Java BitSet previousClearBit()方法

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

Bitset.previousClearBit()

该方法用于查找在作为参数传递的索引上或之前发生的错误位。该方法返回在指定的起始索引上或之前发生的最接近的被设置为假的位的索引。如果没有这样的位存在,或者如果给了-1作为起始索引,那么就会返回-1。

语法。

public int previousClearBit(int fromIndex)

参数。这个方法需要fromIndex,这是开始检查的索引(包括在内)。

返回值。该方法返回前一个清零位的索引,如果没有这个位,则返回-1。

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

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

程序1:

// Java program illustrating Bitset
// previousClearBit() 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 previousClearBit() on bitsets
        System.out.println("Previous Clear Bit of bs1"
+ bs1.previousClearBit(0));
        System.out.println("Previous Clear Bit of bs2"
+ bs2.previousClearBit(5));
        System.out.println("Previous Clear Bit of bs3"
+ bs3.previousClearBit(3));
          
    }
} 

输出:

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

程序2:要显示IndexOutOfBoundException。

// Java program illustrating Bitset
// previousClearBit() 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.previousClearBit(-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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程