Random.nextInt()其实是有规律的,当知道种子值后,别人就可以推断出随机数的值
例如
public static void main(String[] args) {
Random random1 = new Random(10);
Random random2 = new Random(10);
for (int i = 0; i<10;i++){
System.out.println(random1.nextInt(10));
}
System.out.println("=========");
for (int i = 0; i<10;i++){
System.out.println(random2.nextInt(10));
}
}
输出:

结果一样,当不写上种子值后,底层会以当前时间作为种子值
Math.random()这个方法里没有规律
for (int i = 0; i<10;i++){
System.out.println(Math.random()*10);
}
System.out.println("=========");
for (int i = 0; i<10;i++){
System.out.println(Math.random()*10);
}
输出:

总结:工作中不适合用random.nextInt
本文深入探讨了Java中Random类的nextInt()方法与Math.random()方法在生成随机数时的区别。通过实例演示,揭示了nextInt()方法在指定种子值的情况下生成的随机数序列是可以预测的,而Math.random()则提供了更不可预测的随机性。
692

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



