Java BitSet strange behavior -


based on javadoc, following code should print 6. however, outputs 3 no apparent reason.

import java.util.*; public class bitsetstrangeness{     public static void main(string[] args){         bitset foo = new bitset();         int[] arbitrary = new int[] {     0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,1,0,0,0,0,1,1,0,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1         };         (int = 0; < arbitrary.length; i++)             if (arbitrary[i] == 1) foo.set(i);             else foo.clear(i);         system.out.println(foo.get(15,21).length());     } } 

can explain a) why seeing behavior , b) how can modify code fix extracted bitset of length 6 instead of 3?

from the javadoc :

returns "logical size" of bitset: index of highest set bit in bitset plus one.

the length counts set bits.

the bits [0, 0, 1, 0, 0, 0, 0], false after third one, hence returned length.

you have nothing : bitset fine, have been clear if had used size method.


Comments