Any quick method to count the number of set bits in a BitSet other than the usual 'keep a counter' method?
Asked
Active
Viewed 9,627 times
3 Answers
44
The cardinality() method returns the number of set bits.

mwfearnley
- 3,303
- 2
- 34
- 35

pwc
- 7,043
- 3
- 29
- 32
-
3If you were wondering how this is implemented: It does not keep an internal counter, it loops over the `long[]` that is used to hold the bits and calls `Long#bitCount` for each of them. – Thilo Feb 03 '11 at 07:03
-
1under the covers it uses Long.bitCount(). On modern CPU's there is a CPU instruction for this, popcnt. In recent versions of Java, Long.bitCount() uses this instruction. Just use -XX:+UsePopCountInstruction to turn it on (this is the default in recent versions of Java) – Karl Mar 19 '17 at 23:04
3
(Assuming you don't want to call cardinality())
int count = 0;
for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1)) {
count++;
}

Ron
- 1,932
- 20
- 17
1
BitSet B1 = new BitSet(3);
B1.set(0);
B1.cardinality();
Output:
1

Pang
- 9,564
- 146
- 81
- 122

Aditya Parmar
- 1,139
- 13
- 22
-
5This doesn't really add much beyond the answer referring to this method posted 6 years ago. – Bernhard Barker Jun 24 '17 at 20:23
-
I disagree with @Dukeling. One - it uses BitSet's API. Two - it's one method call, not 4 lines with a loop. This is the correct answer IMO, previous answer is a brute force approach. – vacant78 May 18 '18 at 20:37
-
@vacant78 I was referring to [the other answer](https://stackoverflow.com/a/4883196/1711796), which references the same method, with a link to the docs and a brief explanation of what it does. – Bernhard Barker May 21 '18 at 07:44
-
@Dukeling - clearly, I had a bad moment there, unable to see the best (and highest voted) answer... my mistake. – vacant78 May 21 '18 at 10:47