Using a for loop to iterate over a BitSet

Hi all,

Does anyone have an straightforward way of using a 'for' loop to iterate over a BitSet and return the indexes of only the bits that are set to 'true'. I know you can use the nextSetBit() method however you must also pass the starting index each time, I am unsure as to how you form a 'for' statement to do this.

Any help would be much appreciated.

Niall

[392 byte] By [Niall7890a] at [2007-11-26 13:56:27]
# 1

int setBits = new int[bitSet.cardinality()];

int j = 0;

for (int i = 0; i < bitSet.length; i++)

{

if (bitSet.get(i))

{

setBits[j++] = i;

}

}

setBits will contain the indexes of the bits that are set to true.

doremifasollatidoa at 2007-7-8 1:35:58 > top of Java-index,Java Essentials,New To Java...
# 2

See API documentation:

http://java.sun.com/javase/6/docs/api/java/util/BitSet.html#nextSetBit(int)

for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1)) {

// operate on index i here

}

govisagod512a at 2007-7-8 1:35:58 > top of Java-index,Java Essentials,New To Java...
# 3

> See API documentation:

> [url]http://java.sun.com/javase/6/docs/api/java/util/BitSet.html#nextSetBit(int)[/url]

Interesting. They formatted that example a lot better in Java 6 docs than they did in the Java 5 [or Java 1.4] docs. I just made up my own example without looking at that nextBitSet documentation, anyway.

The example in the API could be mixed with my example to return an array of indexes of the bits that are set.

doremifasollatidoa at 2007-7-8 1:35:58 > top of Java-index,Java Essentials,New To Java...
# 4
Thanks a million both,I really feel like an idiot - I have been using an older API and just checked out the method description that you have linked to - exactly what I was looking for! - in black and white - Doh!Thanks again both for the repliesNiall
Niall7890a at 2007-7-8 1:35:58 > top of Java-index,Java Essentials,New To Java...