當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java BitSet nextSetBit()用法及代碼示例


BitSet是java.util包中定義的類。它創建一個由布爾值表示的位數組。

先決條件:Java BitSet |套裝1

nextSetBit()方法:
BitSet類中的此方法用於返回設置為true的第一位的索引,該索引出現在指定的起始索引上或之後。如果不存在這樣的位,則返回-1。


用法:

public int nextSetBit(int fromIndex)

參數:此方法采用強製性參數fromIndex,該參數是從(包括)開始檢查下一個真實位的索引。

返回值:此方法返回下一個設置位的索引;如果不存在該位,則返回-1

異常:如果指定的索引為負,則此方法將引發IndexOutOfBoundsException。

注意:要遍曆BitSet中的真實位,請使用以下循環:

for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1)) {
     // operate on index i here
 }

示例1:要顯示nextSetBit()函數的實現:

// Java program illustrating Bitset 
// nextSetBit() 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 nextSetBit() on bitsets 
        System.out.println(bs1.nextSetBit(2)); 
        System.out.println(bs2.nextSetBit(0)); 
        System.out.println(bs3.nextSetBit(3)); 
    } 
}
輸出:
bs1 : {0, 1, 2, 4}
bs2 : {1, 2, 3, 4, 5, 6, 12}
bs3 : {}
2
1
-1

示例2:要顯示IndexOutOfBoundException:

// Java program illustrating Bitset 
// nextSetBit() 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(); 
  
        /* 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); 
  
        try { 
            // Passing -1 as parameter 
            System.out.println(bs1.nextSetBit(-1)); 
        } 
        catch (Exception e) { 
            System.out.println("Exception when "
                               + "negative index is passed "
                               + "as parameter : " + e); 
        } 
    } 
}
輸出:
bs1 : {0, 1, 2, 4}
bs2 : {1, 2, 3, 4, 5, 6, 12}
Exception when negative index is passed as parameter : java.lang.IndexOutOfBoundsException: fromIndex 


相關用法


注:本文由純淨天空篩選整理自barykrg大神的英文原創作品 BitSet nextSetBit() method in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。