简体   繁体   English

Java中的BitSet类

[英]BitSet Class in java

While I was reading about BitSet Class in java, I came across below example. 当我阅读Java中的BitSet类时,遇到了以下示例。 is logic of BitSet class and, or & xor is same as logic gates logic? 是SetSet类的逻辑和,或&xor与逻辑门逻辑相同?

can someone please explain me how or method works in above example ? 有人可以在上面的示例中解释我的工作方式或方法吗? because when I read in oracle docs about or method it says:: 因为当我阅读有关或方法的oracle文档时,它说:

public void or(BitSet set) 公共无效或(BitSet设置)

Performs a logical OR of this bit set with the bit set argument. 使用bit set参数对该位设置执行逻辑或。 This bit set is modified so that a bit in it has the value true if and only if it either already had the value true or the corresponding bit in the bit set argument has the value true. 修改此位集,以便仅当且仅当它已经具有值true或位集参数中的相应位具有值true时,其中的位才具有true值。

Parameters:set - a bit set 参数:set-一点设置

Below are the codes:: 以下是代码::

import java.util.BitSet;

public class BitSetDemo {

  public static void main(String args[]) {
     BitSet bits1 = new BitSet(16);
     BitSet bits2 = new BitSet(16);

     // set some bits
     for(int i=0; i<16; i++) {
        if((i%2) == 0) bits1.set(i);
        if((i%5) != 0) bits2.set(i);
     }
     System.out.println("Initial pattern in bits1: ");
     System.out.println(bits1);
     System.out.println("\nInitial pattern in bits2: ");
     System.out.println(bits2);

     // AND bits
     bits2.and(bits1);
     System.out.println("\nbits2 AND bits1: ");
     System.out.println(bits2);

     // OR bits
     bits2.or(bits1);
     System.out.println("\nbits2 OR bits1: ");
     System.out.println(bits2);

     // XOR bits
     bits2.xor(bits1);e
     System.out.println("\nbits2 XOR bits1: ");
     System.out.println(bits2);
  }
}

The Output of above program is

Initial pattern in bits1:
{0, 2, 4, 6, 8, 10, 12, 14}

Initial pattern in bits2:
{1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14}

bits2 AND bits1:
{2, 4, 6, 8, 12, 14}

bits2 OR bits1:
{0, 2, 4, 6, 8, 10, 12, 14}

bits2 XOR bits1:
{}

so in the above example result of or should be {0,1,2,3,4,6,7,8,9,10,11,12,13,14} according to oracle docs instead of {0, 2, 4, 6, 8, 10, 12, 14}. or am I misunderstood the explanation?

Really appreciate the help.

The problem is that you compute bits2.or(bits1) with the value of bits2 already modified from the and call. 问题是,您使用已经从and调用中修改的bits2的值来计算bits2.or(bits1) Instead of calling or , and , and xor directly on bits2 , try using a separate copy of bits2 for each test. 代替直接在bits2上调用orandxor ,请尝试对每个测试使用单独的bits2副本。

The value of bits2 has been altered during the and operation by the call bits2.and(bits1) . and操作期间and通过调用bits2.and(bits1)更改了bits2的值。 The value of bits2 is again altered by the following or and xor operations by the calls bits2.or(bits1) and bits2.xor(bits1) 再次通过调用bits2.or(bits1)bits2.xor(bits1)的以下orxor操作来更改bits2的值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM