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();

欢迎 意见 建议 指正 交流。

原文地址:https://www.cnblogs.com/xirtam/p/3145489.html