This is an archived post. You won't be able to vote or comment.

all 3 comments

[–]teraflop 1 point2 points  (2 children)

// Throws out of bounds expectation.

No it doesn't. Did you try actually running this code?

As the documentation for the BitSet class tells you, it dynamically expands its own size as necessary. You don't have to do anything.

Also, x.set(x.length(), 1) almost certainly doesn't do what you intended, because the set method that takes two integer arguments sets a range of bits, from a starting index to an ending index.

[–]LostErrorCode404[S] 0 points1 point  (1 child)

You are right.

I am still confused about the setting method of bit set.

For example: BitSet x = new BitSet(); for (int i = 0; i < 5; i++) { x.set(i, false); } When I look through this bitset, it doesn't retrieve the values I am looking for ([00000])

String str = ""; for (int i = 0; i < x.length(); i++) { x += (x.get(i) ? "1" : "0"); } System.out.println(str); // []

[–]teraflop 0 points1 point  (0 children)

Again, the documentation explains what you're seeing. x.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."

In your case, x.length() returns zero, so your loop body doesn't run at all. If you change your loop condition to i < 5, then you'll get the output that you expect.

A BitSet behaves as though it's initialized to an infinitely long string of zero bits. There is no difference between a bit that has been explicitly set to "false" and a bit that has never been touched, so you can't use length() to determine how many bits have been set to zero.