Java:可以(new Random())。nextInt(5)总是返回相同的数字? [英] Java: Can (new Random()).nextInt(5) always return the same number?

查看:1052
本文介绍了Java:可以(new Random())。nextInt(5)总是返回相同的数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时候这段代码总是返回相同的数字(有时它可以正常工作):

Sometimes this piece of code always returns the same number (and sometimes it works fine):

(new Random()).nextInt(5)

我怀疑问题所在 - 它可能总是创建一个新的随机与同一种子。那么什么是最好的解决方案:

I have suspicions where the problem is - it probably always creates a new Random with the same seed. So what would be the best solution:


  • 为Random()创建静态变量,而
    则使用它。

  • 使用Math.random()* 5
    (看起来它在内部使用静态var

还是其他什么?我不需要任何看似随意的东西。

or something else? I don't need anything fancy just something that looks random.

如果有人可以解释为什么原始代码有时会起作用而有时却没有。

Also it would be helpful if someone can explain why the original code sometimes works and sometimes it doesn't.

谢谢。

推荐答案

java.util.Random的javadoc很明显:

The javadoc for java.util.Random is clear:


如果使用相同的种子创建两个Random实例
,并且相同的
序列方法调用每个都是
,它们将生成并返回
相同的数字序列。

If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers.

默认值构造函数也很清楚:

The default constructor is also clear:


创建一个新的随机数生成器。
此构造函数将
随机数生成器的种子设置为值
很可能与此构造函数的任何
其他调用不同。

Creates a new random number generator. This constructor sets the seed of the random number generator to a value very likely to be distinct from any other invocation of this constructor.

换句话说,没有保证。

如果您需要更随机的算法,请使用java.security。 SecureRandom。

If you need a more random algorithm, use java.security.SecureRandom.

这篇关于Java:可以(new Random())。nextInt(5)总是返回相同的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆