Java BitSet and() 方法



描述

Java BitSet and(BitSet set) 方法對目標位集與引數位集執行邏輯與運算。此位集被修改,使其中的每個位僅當它最初的值為真並且引數位集中對應的位的值也為真時,其值才為真。

宣告

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

public void and(BitSet set)

引數

set − 位集

返回值

此方法不返回值。

異常

對位集執行與運算示例

以下示例演示了 Java BitSet and() 方法的使用。我們建立了兩個 BitSet。我們使用 set() 方法根據索引為 BitSet 物件設定給定索引處的真值,並使用 and() 方法執行運算並列印更新後的位集。

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);

      // perform and operation between two bitsets
      bitset1.and(bitset2);

      // print the new bitset1
      System.out.println(bitset1);
   }
}

輸出

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

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

對位元組位集執行與運算示例

以下示例演示了 Java BitSet and() 方法的使用。我們使用 byte[] 建立了兩個 BitSet,並使用 and() 方法執行運算並列印更新後的位集。

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);

      // perform and operation between two bitsets
      bitset1.and(bitset2);

      // print the new bitset1
      System.out.println(bitset1);
   }
}

輸出

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

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

對長整數位集執行與運算示例

以下示例演示了 Java BitSet and() 方法的使用。我們使用 long[] 建立了兩個 BitSet,並使用 and() 方法執行運算並列印更新後的位集。

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);

      // perform and operation between two bitsets
      bitset1.and(bitset2);

      // print the new bitset1
      System.out.println(bitset1);
   }
}

輸出

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

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