java的Random
2024-08-26 16:51:21
首先,Point类
public class Point {
int x, y; public Point(int x, int y) {
this.x = x;
this.y = y;
} boolean isSame() {
return x == y;
}
}
测试代码A:
public class RandomTest { public static Random random = new Random();
public static void main(String[] args) {
int x = 0, y = 0;
List<Point> points = new ArrayList<Point>();
for (int i = 0; i < 100000; i++) {
x = new Random().nextInt(20);
y = new Random().nextInt(20);
points.add(new Point(x, y));
}
System.out.println(getSameCount(points)); } public static int getSameCount(List<Point> li) {
int count = 0;
for (Point point : li) {
if (point.isSame())
count++;
}
return count;
} }
测试代码B将Main方法替换为
public static void main(String[] args) {
int x = 0, y = 0;
List<Point> points = new ArrayList<Point>();
for (int i = 0; i < 100000; i++) {
x = random.nextInt(100);
y = random.nextInt(100);
points.add(new Point(x, y));
}
System.out.println(getSameCount(points)); }
经测试
A代码打印结果在3000左右
B代码打印结果在1000左右
查了一些资料
大概是因为同时创建的两个Random对象,产生随机数的算法会比较类似,和创建对象时的时间戳有关系,所以产生的随机数相同的几率也比较大。
所以程序中应该尽量避免使用多个Random对象,或者直接使用Math.random();
欢迎 意见 建议 指正 交流。
最新文章
- Ninject之旅之四:Ninject模块
- 理解 charging ic spec
- C/C++相对论——C++中为什么要使用异常?
- php在centos下的脚本没有解析的问题
- IDEA调试javaScript
- 第一个MySQL 存储过程
- IE浏览器Ajax缓存问题小结
- c# excel sheep 导出
- 每天学点Linux:七
- redis(四)redis与Mybatis的无缝整合让MyBatis透明的管理缓存
- VC 绘图技巧--自定义形状图形
- udev实现热插拔
- STM32F4系列单片机上使用CUBE配置MBEDTLS实现pem格式公钥导入
- Python generator和yield介绍
- MyBatis进阶(三)
- CSS垂直居中查询宝典
- Symmetric Tree leetcode java
- 原生JavaScript实现新手引导效果(第二个玩具)
- easyUi 的DataGrid的绑定
- SQL触发器实例(上)