相关疑难解决方法(0)

随机长,可以连续两次相同的数字

我想知道当前java 1.7的Random类实现,下面的代码是否有可能生成相同随机长度的两倍?

Random rand = new Random((long) "some seed".hashCode());
while(rand.nextLong() != rand.nextLong()){

}

System.out.println("Will this text ever be on the console?");
Run Code Online (Sandbox Code Playgroud)

nextLong()和next()的Java源代码;

public long nextLong(){
    return ((long) next(32) << 32) + next(32);
}

protected synchronized int next(int bits){
    seed = (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1);
    return (int) (seed >>> (48 - bits));
}
Run Code Online (Sandbox Code Playgroud)

我会用false回答这个问题,因为我认为java使用的随机方法在2 ^ 48周期内不会重复相同的数字,所以它永远不会在一行中生成两个相同的数字.它是否正确?

java random

14
推荐指数
2
解决办法
2473
查看次数

标签 统计

java ×1

random ×1