Skip to main content

Iterating a BitSet

1 reply [Last post]
arya_18
Offline
Joined: 2003-06-12

I recently happened to use BitSet for implementing a sorting algorithm (The one mentioned in Programming Pearls book!!) and saw that the BitSet class does not come with an iterator. The javadoc does suggest a mechanism to iterate but it would be nice if this could be encapsulated in an iterator.My suggestion is an impl like this:

public class BitSetIterator {
private BitSet bitSet;
private int indexOfLastSetBit;

public BitSetIterator(BitSet bitSet) {
this.bitSet = bitSet;
}

public boolean hasMoreSetBits() {
return (bitSet.nextSetBit(indexOfLastSetBit)!= -1);
}

public int nextSetIndex() {
int index = bitSet.nextSetBit(indexOfLastSetBit);
indexOfLastSetBit = index + 1;
return index;
}
}

Of course more useful methods could be added to this like moving over clear bits, all bits etc.

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
lucretius2
Offline
Joined: 2004-12-19

This would be (mostly) solved by the following idea:

http://forums.java.net/jive/thread.jspa?threadID=295

Integer and Long would implement List, and would thus be iterable as if they were fixed-size arrays of Boolean values. They could replace BitSet for up to 64 bits. Perhaps this would show the way for a new class BitArray (implements List ) which could be used for more than 64 bits; you could use Integer or Long for efficiency if you knew fewer than 32 or 64 bits were needed.