首先,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();

欢迎 意见 建议 指正 交流。

最新文章

  1. Ninject之旅之四:Ninject模块
  2. 理解 charging ic spec
  3. C/C++相对论——C++中为什么要使用异常?
  4. php在centos下的脚本没有解析的问题
  5. IDEA调试javaScript
  6. 第一个MySQL 存储过程
  7. IE浏览器Ajax缓存问题小结
  8. c# excel sheep 导出
  9. 每天学点Linux:七
  10. redis(四)redis与Mybatis的无缝整合让MyBatis透明的管理缓存
  11. VC 绘图技巧--自定义形状图形
  12. udev实现热插拔
  13. STM32F4系列单片机上使用CUBE配置MBEDTLS实现pem格式公钥导入
  14. Python generator和yield介绍
  15. MyBatis进阶(三)
  16. CSS垂直居中查询宝典
  17. Symmetric Tree leetcode java
  18. 原生JavaScript实现新手引导效果(第二个玩具)
  19. easyUi 的DataGrid的绑定
  20. SQL触发器实例(上)

热门文章

  1. LightOJ1191 Bar Codes(DP)
  2. 在iOS开发中使用FMDB
  3. QDir, QFileInfo 和 QDirIterator 区别
  4. openstack创建虚拟机的步骤
  5. [转] - 经典SQL语句大全
  6. 文件上传\&quot;&gt;将在3秒钟后返回前页
  7. 微博java SDK介绍及使用说明
  8. iOS textFiled 在storyBoard中的使用
  9. JavaScript系列:event.bubbles属性(并不是所有的事件都具有冒泡)
  10. JS对json对象的调用成员2种方式