Java BitSet get(int bitIndex) 方法



描述

Java BitSet get(int bitIndex) 方法返回指定索引位的位的值。如果索引為 bitIndex 的位當前在此 BitSet 中已設定,則值為 true;否則,結果為 false。

宣告

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

public boolean get(int bitIndex)

引數

bitIndex − 位索引。

返回值

此方法返回指定索引位的位的值。

異常

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

Java BitSet get(int fromIndex, int toIndex) 方法

描述

java.util.BitSet.get(int fromIndex,int toIndex) 方法返回一個新的 BitSet,該 BitSet 由此 BitSet 中從 fromIndex(包含)到 toIndex(不包含)的位組成。

宣告

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

public BitSet get(int fromIndex,int toIndex)

引數

  • fromIndex − 要包含的第一個位的索引。

  • toIndex − 要包含的最後一個位之後的索引。

返回值

此方法返回從此 BitSet 的一個範圍內的新的 BitSet。

異常

IndexOutOfBoundsException − 如果 fromIndex 為負數,或 toIndex 為負數,或 fromIndex 大於 toIndex。

從 BitSet 中按索引獲取位示例

以下示例演示了 Java BitSet get(bitIndex) 方法的用法。我們正在建立一個 BitSet。我們使用 set() 方法呼叫在 BitSet 物件中設定 true 值,並使用 get(bitIndex) 方法列印一個 true 位和一個 false 位的值。

package com.tutorialspoint;

import java.util.BitSet;

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

      // create a bitset
      BitSet bitset = new BitSet();

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

      // print the set
      System.out.println("Bitset:" + bitset);

      // print the value at index 2
      System.out.println(bitset.get(2));

      // print the value at index 7
      System.out.println(bitset.get(7));
   }
}

輸出

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

Bitset:{0, 1, 2, 3, 4, 5}
Bitset:{0, 1, 3, 4, 5}

從 BitSet 中按索引獲取多個位示例

以下示例演示了 Java BitSet get(fromIndex, toIndex) 方法的用法。我們正在建立一個 BitSet。我們使用 set() 方法呼叫在 BitSet 物件中設定 true 值,並使用 get(fromIndex, toIndex) 方法獲取一個較小的 bitset 並列印它。

package com.tutorialspoint;

import java.util.BitSet;

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

      // create a bitset
      BitSet bitset = new BitSet();

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

      // print the set
      System.out.println("Bitset:" + bitset);     

      // print the bitset from 3 to 6
      System.out.println("Bitset:" + bitset.get(3,6));
   }
}

輸出

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

Bitset:{0, 1, 2, 3, 4, 5}
Bitset:{0, 1, 2}

從位元組的 BitSet 中按索引獲取位示例

以下示例演示了 Java BitSet get(bitIndex) 方法的用法。我們使用 byte[] 建立兩個 BitSet,並使用 get(bitIndex) 方法列印一個 true 位和一個 false 位的值。

package com.tutorialspoint;

import java.util.BitSet;

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

      // create a bitset
      BitSet bitset = BitSet.valueOf(new byte[] { 0, 1, 2, 3, 4, 5 });

      // print the set
      System.out.println("Bitset:" + bitset);

      // print the value at index 17
      System.out.println(bitset.get(17));

      // print the value at index 18
      System.out.println(bitset.get(18));
   }
}

輸出

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

Bitset:{8, 17, 24, 25, 34, 40, 42}
true
false
java_util_bitset.htm
廣告