BitSet logically represents a “vector of bits that grows as needed” (javadoc).
When you create it via new BitSet(), you have all bits set to 0 (false).
0 5 10
| | |
000000000000... (virtually infinite sequence)
Using set(x) you set to 1 (true) the bit at position x (where the first position is 0); e.g. in your code you enable bits 3, 5 and 9.
0 5 10
| | |
000101000100...
toString() reports the list of bits set to 1, i.e. 3, 5 and 9 in the example.
toByteArray() converts the contents of the BitSet to a sequence of byte values, each containing the value of 8 contiguous bits, in little-endian order (i.e. starting from least indices in the BitSet). The output {40, 2} in your example comes from:
7 0 15 8 <- position in BitSet
| | | |
{00101000 , 00000010} <- toByteArray(), binary
| |
{ 40 , 2 } <- toByteArray(), decimal
Hope this helps.
2
solved Why Bitset allows values distinct from 1 and 0?