简体   繁体   中英

How does the cardinality works in java Bitset?

import java.util.*;
public class Main {
public static void main(String[] args)
{

BitSet bs1 = new BitSet();
BitSet bs2 = new BitSet();


bs1.set(0);
bs1.set(1);
bs1.set(2);
bs1.set(4);

bs2.set(0);
bs2.set(0);
bs2.set(0);
bs2.set(0);
bs2.set(0);
bs2.set(0);


System.out.println("bs1 : " + bs1);
System.out.println("bs2 : " + bs2);



System.out.println(bs1.cardinality());
System.out.println(bs2.cardinality());

}
}

In this above code the cardinality of bitset bs1 is found to be 4 and the bs2 is found to be 1.how does the cardinality comes as 1 for bs2?

Because.. that's what you programmed. I think I see where you're confused.

This:

bs2.set(0);
bs2.set(0);
bs2.set(0);
bs2.set(0);
bs2.set(0);
bs2.set(0);

Is 1 line that does something (the first .set(0) call), and then 5 lines that do nothing whatsoever. bs2.set(0) sets the 0th bit to 1. It doesn't set "the next bit". Hence, bs2 has a single bit that is set: The 0th bit. Hence, its cardinality, which counts the amount of bits that are set, is 1.

This:

bs1.set(0);
bs1.set(1);
bs1.set(2);
bs1.set(4);

Simply sets the 0th, 1th, 2nd, and 4th bit. That sets a total of 4 bits, hence, cardinality of 4. The bits are, in order from low to high: 11101000.

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