简体   繁体   中英

BitSet Class in java

While I was reading about BitSet Class in java, I came across below example. is logic of BitSet class and, or & xor is same as logic gates logic?

can someone please explain me how or method works in above example ? because when I read in oracle docs about or method it says::

public void or(BitSet set)

Performs a logical OR of this bit set with the bit set argument. 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.

Parameters:set - a bit 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. Instead of calling or , and , and xor directly on bits2 , try using a separate copy of bits2 for each test.

The value of bits2 has been altered during the and operation by the call bits2.and(bits1) . The value of bits2 is again altered by the following or and xor operations by the calls bits2.or(bits1) and bits2.xor(bits1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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