关于构造方法Random(long seed)的理解
无参构造方法使用的默认参数是系统当前的毫秒数。使用同一数值的种子参数,生成的随机数也是一样的。
代码如下所示:
import java.util.Random; public class Test04 { public static void main(String[] args) { // TODO Auto-generated method stub Random r1 = new Random(20); for(int i = 0 ; i < 7; i++) { System.out.print(r1.nextInt() + " "); } System.out.println(); Random r2 = new Random(20); for(int i = 0; i < 7; i++) { System.out.print(r2.nextInt() + " "); } } }
运行结果如下所示:
什么是种子 seed 呢?
seed 是 Random 生成随机数时使用的参数:
Random 中最重要的就是 next(int) 方法,使用 seed 进行计算:
protected synchronized int next(int bits) { seed = (seed * multiplier + 0xbL) & ((1L << 48) - 1); return (int) (seed >>> (48 - bits)); }
其他 nextXXX 方法都是调用的 next()。
比如 nextInt(int):
public int nextInt(int n) { if (n <= 0) { throw new IllegalArgumentException("n <= 0: " + n); } if ((n & -n) == n) { //调用 next() return (int) ((n * (long) next(31)) >> 31); } int bits, val; do { bits = next(31); val = bits % n; } while (bits - val + (n - 1) < 0); return val; }