Randomly initialize BitSet in JAVA

半世苍凉 提交于 2020-01-03 12:29:09

问题


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

Thanks in advance.


回答1:


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




回答2:


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:


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.



来源:https://stackoverflow.com/questions/8557857/randomly-initialize-bitset-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!