Get all Indexes of the set bits in a BitSet

myborobudur picture myborobudur · Mar 13, 2013 · Viewed 9.9k times · Source

I'm looking for a fast algorithm with gives me all the indexes of the set bits in a BitSet object. This is slow:

BitSet bitSet = ...
Collection<Integer> indexes = new ArrayList<Integer>(bitSet.cardinality());
int nextSetBit = bitSet.nextSetBit(0);
for (int i = 0; i < bitSet.cardinality(); ++i ) {
    indexes.add(nextSetBit);
    nextSetBit = bitSet.nextSetBit(nextSetBit + 1);
}
...

Any help is appreciated!

Answer

Louis Wasserman picture Louis Wasserman · Mar 13, 2013

No need to use bitSet.cardinality() at all:

for (int i = bitSet.nextSetBit(0); i != -1; i = bitSet.nextSetBit(i + 1)) {
    indexes.add(i);
}