質問

Based on the Javadoc, the following code should print 6. However, it outputs 3 for 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
        };
        for (int i = 0; i < arbitrary.length; i++)
            if (arbitrary[i] == 1) foo.set(i);
            else foo.clear(i);
        System.out.println(foo.get(15,21).length());
    }
}

Can anyone explain a) why I am seeing this behavior and b) How I can modify the code to fix it so that the extracted Bitset is of length 6 instead of 3?

役に立ちましたか?

解決

From the javadoc :

Returns the "logical size" of this BitSet: the index of the highest set bit in the BitSet plus one.

The length only counts the set bits.

The bits are [0, 0, 1, 0, 0, 0, 0], that is false after the third one, hence the returned length.

You have nothing to do : your bitSet is fine, as would have been clear if you had used the size method.

他のヒント

Why it should return 6? Let's see:

  1. foo.get(15,21) returns word equals 4. In binary representation it is just 100.

  2. Let's read javadoc of length() method of BitSet class:

Returns the "logical size" of this BitSet: the index of the highest set bit in the BitSet plus one. Returns zero if the BitSet contains no set bits.

Ok, we can now check it for 100: the highest set bit is 2 (counting from 0), plus one it will be 3. Everything is correct.

Javadoc for BitSet#length(),says Returns the "logical size" of this BitSet: the index of the highest set bit in the BitSet plus one. Returns zero if the BitSet contains no set bits.

In your case the foo.get(15,21) gives a BitSet : [0, 0, 1, 0, 0, 0, 0]. Hence the result is 2+1=3.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top