Randomly initialize BitSet in JAVA

2019-06-20 17:54发布

I have BitSet which has to be initialized randomly. Is there any method to do that?

Thanks in advance.

标签: java random
3条回答
走好不送
2楼-- · 2019-06-20 18:33

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.

查看更多
手持菜刀,她持情操
3楼-- · 2019-06-20 18:33

There is no such constructor. What you'd have to do is create a BitSet and then in a loop set all bits to random values.

查看更多
一纸荒年 Trace。
4楼-- · 2019-06-20 18:38

Just go through BitSet and call nextBoolean() of the Random class.

查看更多
登录 后发表回答