Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why XOR value is empty in BitSet in java?

I just entered into Advance Java. I don’t know why xor() function returning empty set.
As i know, XOR return zero for two same bits and 1 for two different bits. So, if I XOR first two bit from Bits One and Bits two that is, 0 and 1 respectively, why does it return empty set. Please explain in detail, if possible and/or necessary.

Code

public class LearnBitSet {
public static void main(String[] args) {
BitSet bits1 = new BitSet(32);
BitSet bits2 = new BitSet(32);
for (int bitCount = 0; bitCount < 32; bitCount++) {
        if (bitCount % 2 == 0){
            bits1.set(bitCount);
        }
        if (bitCount % 5 != 0){
            bits2.set(bitCount);
        }
    }
System.out.println("Bits One = " + bits1);
System.out.println("Bits Two = " + bits2);
// AND
bits1.and(bits2);
System.out.println("ADD = " +bits1);

// OR
bits1.or(bits2);
System.out.println("OR = "+bits1);
// XOR

bits1.xor(bits2);
System.out.println("XOR = "+bits1);
}

}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

OUTPUT

Bits One = {0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30}
Bits Two = {1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14, 16, 17, 18, 19, 21, 22, 23, 24, 26, 27, 28, 29, 31}
ADD = {2, 4, 6, 8, 12, 14, 16, 18, 22, 24, 26, 28}
OR = {1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14, 16, 17, 18, 19, 21, 22, 23, 24, 26, 27, 28, 29, 31}
XOR = {}

EDIT 1st
Also, there is problem that Cardinality is 0. Why ? In output, there are so many but bits1.cardinality() returns zero. Is there any detailed resource Online to understand BitSet.

>Solution :

You can see that the contents of bits1 are exactly the same as bits2 after you’ve done the OR operation:

...
Bits Two = {1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14, 16, 17, 18, 19, 21, 22, 23, 24, 26, 27, 28, 29, 31}
...
OR = {1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14, 16, 17, 18, 19, 21, 22, 23, 24, 26, 27, 28, 29, 31}

So if you’re doing an XOR operation where both operands are the same, you’ll get "0" or "False" by definition (see the truth table), or in this case a BitSet with all bits set to false.

Finally, according to the documentation of toString(), an empty BitSet is printed as {}

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading