zoukankan      html  css  js  c++  java
  • java的Random

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

    欢迎 意见 建议 指正 交流。

  • 相关阅读:
    常用正则表达式
    玉洁哥的设计模式指摘
    jquery makearray()使用
    html/css技巧总结
    json 数组 对象 xml 之间转换(待补充)
    Html5 Geolocation获取地理位置信息
    JSON.stringify 应用
    url操作一网打尽(一)
    jquery选择器
    JavaScript Window Location
  • 原文地址:https://www.cnblogs.com/xirtam/p/3145489.html
Copyright © 2011-2022 走看看