随机类表现奇怪吗? [英] Random class acting odd?
问题描述
在此代码中:
Random random = new Random(441287210);
for(int i=0;i<10;i++)
System.out.print(random.nextInt(10)+" ");
}
输出 1 1 1 1 1 1 1每次1 1 1
。
这是为什么?不是随机
应该......好吧......随机?我认为 Random
类使用 System.nanoTime
,因此输出通常应该是随机的。有人可以解释一下吗?
Why is this? Isn't Random
supposed to be... well... random? I thought that the Random
class use System.nanoTime
, so the output should be generally random. Can someone please explain?
推荐答案
Random
类生成的值是伪随机:它们是使用基于种子值的确定性算法创建的。通常(例如,如果使用无参数构造函数),使用当前时间初始化种子,这显然是唯一值。因此,会生成一个唯一的随机序列。
The values generated by Random
class are pseudo-random: they are created using a deterministic algorithm, based on seed value. Typically (if you use parameterless constructor, for example) the seed is initialized using current time, which is obviously a unique value. Hence a unique, 'random' sequence is generated.
这里使用的是一个常量种子值,它在代码的执行之间不会发生变化。因此,您始终获得相同的序列。恰好这个特定种子的序列是 1 1 1 1 1 1 ...
。
Here you are using a constant seed value which doesn't change between executions of your code. Therefore you always get the same sequence. It just happens that this sequence is 1 1 1 1 1 1 ...
for this particular seed.
这篇关于随机类表现奇怪吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!