-1

so I'm initializing a Bitset variable with a length of 4. When i try to seed this Bitset with the Random's class nextBoolean method. It gives the effect of removing elements. This is more than likely my inexperience with using Bitset. But as far as my understanding each element in the Bitset variable should have a random 0 or 1. Can someone see what it is that I'm doing wrong and explain what that is?

public void seedCandidate()
{
    // Randomly sets bits in the candidate

    for (int i = 0; i < numVals; i++)
        truthVals.set(i, rn.nextBoolean());

}

When I output the length of the bitset it gives random sizes. The length of truthVals(the Bitset variable) should be 4 which is what it got instanced to so it should be {0, 1, 2, 3}. But after the seeding from the method on top I get these different lengths. From different Bitset variables.

{1, 2, 3}, {0, 1, 2, 3}, {0}, {0, 2, 3}

carlos
  • 33
  • 1
  • 4

2 Answers2

2

From the BitSet-javadoc:

  1. public BitSet(int nbits)

    Creates a bit set whose initial size is large enough to explicitly represent bits with indices in the range 0 through nbits-1. All bits are initially false.

  2. public int length()

    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.

  3. public int size()

    Returns the number of bits of space actually in use by this BitSet to represent bit values.

  4. public int cardinality()

    Returns the number of bits set to true in this BitSet.

  5. public void set(int bitIndex, boolean value)

    Sets the bit at the specified index to the specified value.

  6. And of course the mentioned public String toString() ...

So what is the confusion/unexpected?

xerx593
  • 12,237
  • 5
  • 33
  • 64
0

Consider bitset a boolean array. (The implementation of course a long array of bits.)

  • set(7, true) will "add 7 to the set if not already added. "
  • set(7, false) will "remove 7 from the set if already present. "

The unfortunately named methods that might cause confusion:

  • int cardinality() the number of true elements
  • int size() the capacity (reserved bits, "array size")
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138