1 在0-n之间取随机数,使用
java.util.Random r=new java.util.Random();
r.nextInt(n);
而不使用
(int)(r.nextDouble() * n)
If r is a java.util.Random, you can generate a random number from 0 to n-1 using r.nextInt(n), rather than using (int)(r.nextDouble() * n).
2 在实例中修改静态类的属性
public void process(File fs) {
UtilTools.rootPath = "d:/tmp/";
...
This instance method writes to a static field. This is tricky to get correct if multiple instances are being manipulated, and generally bad practice
java.util.Random r=new java.util.Random();
r.nextInt(n);
而不使用
(int)(r.nextDouble() * n)
If r is a java.util.Random, you can generate a random number from 0 to n-1 using r.nextInt(n), rather than using (int)(r.nextDouble() * n).
2 在实例中修改静态类的属性
public void process(File fs) {
UtilTools.rootPath = "d:/tmp/";
...
This instance method writes to a static field. This is tricky to get correct if multiple instances are being manipulated, and generally bad practice
本文介绍了在Java中如何正确地生成指定范围内的随机数,并解释了为什么应选择nextInt(n)而非基于nextDouble的方法。此外,还讨论了在实例方法中修改静态属性的问题及其潜在风险。
1万+

被折叠的 条评论
为什么被折叠?



