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()和Random.nextInt()的生成随机数区别

结果一样,当不写上种子值后,底层会以当前时间作为种子值


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

输出:

Math.random()和Random.nextInt()的生成随机数区别

 

总结:工作中不适合用random.nextInt

相关文章:

  • 2022-01-24
  • 2022-12-23
  • 2022-12-23
  • 2022-02-10
  • 2021-12-18
  • 2021-09-28
  • 2021-08-27
  • 2021-09-19
猜你喜欢
  • 2021-07-04
  • 2021-06-15
  • 2022-12-23
  • 2021-07-19
  • 2021-05-24
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案