Java BitSet previousSetBit() 方法



描述

Java BitSet previousSetBit(int fromIndex) 方法返回在指定起始索引或之前設定第一個為 true 的位的索引。

宣告

以下是 java.util.BitSet.previousSetBit() 方法的宣告

public int previousSetBit(int fromIndex)

引數

fromIndex - 開始檢查的索引(包含)。

返回值

此方法返回前一個已設定位的索引。

異常

IndexOutOfBoundsException - 如果指定的索引為負數。

獲取 BitSet 的前一個已設定位示例

以下示例顯示了 Java BitSet previousSetBit() 方法的使用。我們建立了兩個 BitSet。我們使用 set() 方法呼叫在 BitSet 物件中設定 true 值,並使用 previousSetBit() 方法列印 bitset 的前一個已設定位。

package com.tutorialspoint;

import java.util.BitSet;

public class BitSetDemo {
   public static void main(String[] args) {

      // create 2 bitsets
      BitSet bitset1 = new BitSet();
      BitSet bitset2 = new BitSet();

      // assign values to bitset1
      bitset1.set(0, 6, true);

      // assign values to bitset2
      bitset2.set(2);
      bitset2.set(4);
      bitset2.set(6);
      bitset2.set(8);
      bitset2.set(10);

      // print the sets
      System.out.println("Bitset1:" + bitset1);
      System.out.println("Bitset2:" + bitset2);

      // print the previous set bit
      System.out.println(bitset1.previousSetBit(5));
      System.out.println(bitset2.previousSetBit(10));
   }
}

輸出

讓我們編譯並執行以上程式,這將產生以下結果:

Bitset1:{0, 1, 2, 3, 4, 5}
Bitset2:{2, 4, 6, 8, 10}
5
10

獲取位元組 BitSet 的前一個已設定位示例

以下示例顯示了 Java BitSet previousSetBit() 方法的使用。我們使用 byte[] 建立了兩個 BitSet,並使用 previousSetBit() 方法列印 bitset 的前一個已設定位。

package com.tutorialspoint;

import java.util.BitSet;

public class BitSetDemo {
   public static void main(String[] args) {

      // create 2 bitsets
      BitSet bitset1 = BitSet.valueOf(new byte[] { 0, 1, 2, 3, 4, 5 });
      BitSet bitset2 = BitSet.valueOf(new byte[] { 2, 4, 6, 8, 10 });

      // print the sets
      System.out.println("Bitset1:" + bitset1);
      System.out.println("Bitset2:" + bitset2);

      // print the previous set bit
      System.out.println(bitset1.previousSetBit(42));
      System.out.println(bitset2.previousSetBit(35));
   }
}

輸出

讓我們編譯並執行以上程式,這將產生以下結果:

Bitset1:{8, 17, 24, 25, 34, 40, 42}
Bitset2:{1, 10, 17, 18, 27, 33, 35}
42
35

獲取長整型 BitSet 的前一個已設定位示例

以下示例顯示了 Java BitSet previousSetBit() 方法的使用。我們使用 long[] 建立了兩個 BitSet,並使用 previousSetBit() 方法列印 bitset 的前一個已設定位。

package com.tutorialspoint;

import java.util.BitSet;

public class BitSetDemo {
   public static void main(String[] args) {

      // create 2 bitsets
      BitSet bitset1 = BitSet.valueOf(new long[] { 0, 1, 2, 3, 4, 5 });
      BitSet bitset2 = BitSet.valueOf(new long[] { 2, 4, 6, 8, 10 });

      // print the sets
      System.out.println("Bitset1:" + bitset1);
      System.out.println("Bitset2:" + bitset2);

      // print the previous set bit
      System.out.println(bitset1.previousSetBit(332));
      System.out.println(bitset2.previousSetBit(259));
   }
}

輸出

讓我們編譯並執行以上程式,這將產生以下結果:

Bitset1:{64, 129, 192, 193, 258, 320, 322}
Bitset2:{1, 66, 129, 130, 195, 257, 259}
322
259
java_util_bitset.htm
廣告