zoukankan      html  css  js  c++  java
  • review17

    关于构造方法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;
    }
  • 相关阅读:
    上下文有关文法
    sqlserver cte 速度慢
    hibernate tools eclipse 安装
    sts java nullpointer exception
    Oracle RAC集群体系结构
    bean scope scoped-proxy
    hibernate persist不能插入到表中
    system.out 汉字乱码
    NoSQL数据库(转)
    在PowerShell中获取本地的RAM信息(容量)
  • 原文地址:https://www.cnblogs.com/liaoxiaolao/p/9425020.html
Copyright © 2011-2022 走看看