如果需要产生一个0----N之间随机一个整数,可以写这样的方法
int random(int n){
Random r=new Random();
return Math.abs(r.nextInt())%n;
}
使用这random有三个缺点:
1.如果n为2的乘方,随机序列会重复
2.如果n不是2的乘方,有些数字会更频繁
3.会返回范围之外的数据
解决办法:
r.nextInt(n )
使用ThreadLocalRandom保证
如果需要产生一个0----N之间随机一个整数,可以写这样的方法
int random(int n){
Random r=new Random();
return Math.abs(r.nextInt())%n;
}
1.如果n为2的乘方,随机序列会重复
2.如果n不是2的乘方,有些数字会更频繁
3.会返回范围之外的数据
r.nextInt(n )
使用ThreadLocalRandom保证
本文标题:了解和使用类库
本文链接:https://www.haomeiwen.com/subject/ipavvctx.html
网友评论