I have BitSet which has to be initialized randomly. Is there any method to do that?
Thanks in advance.
Just go through BitSet and call nextBoolean() of the Random class.
If you are using Java 7, you can initialize a random byte array with Random.nextBytes(byte[])
then use the static BitSet.valueOf(byte[])
method to create a BitSet
from the same byte array.
Random rnd = new Random();
// ...
byte[] randomBytes = new byte[NUM_BYTES];
rnd.nextBytes(randomBytes);
return BitSet.valueOf(randomBytes);
Or if you want the proportion of 0
vs. 1
bits to be something other than 50:50, check out an old SO question of mine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With