Java Random 含參與不含參建構函式的區別

來源:互聯網
上載者:User

標籤:protect   gaussian   div   構造方法   test   time()   random   ref   sdn   

##Random 通常用來作為隨機數產生器,它有兩個構造方法:

        Random random = new Random();        Random random2 = new Random(50);

1.不含參構造方法:

public Random() {    setSeed(System.nanoTime() + seedBase);    ++seedBase;}

2.含參構造方法:

public Random(long seed) {    setSeed(seed);}

都調用的 setSeed 方法:

public synchronized void setSeed(long seed) {    this.seed = (seed ^ multiplier) & ((1L << 48) - 1);    haveNextNextGaussian = false;}

###可以看到,不含參構造方法每次都使用目前時間作為種子,而含參構造方法是以一個固定值作為種子

##什麼是種子 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;}

再比如 nextBoolean():

//也是調用的 next()public boolean nextBoolean() {    return next(1) != 0;}

##舉個栗子:

@Testpublic void testRandomParameter(){    System.out.println("Random 不含參構造方法:");    for (int i = 0; i < 5; i++) {        Random random = new Random();        for (int j = 0; j < 8; j++) {            System.out.print(" " + random.nextInt(100) + ", ");        }        System.out.println("");    }    System.out.println("");    System.out.println("Random 含參構造方法:");    for (int i = 0; i < 5; i++) {        Random random = new Random(50);        for (int j = 0; j < 8; j++) {            System.out.print(" " + random.nextInt(100) + ", ");        }        System.out.println("");    }}

分別用含參構造方法和不含參構造方法建立 5 個隨機產生器對象,每個隨機產生器再生產 8 個隨機數,對比下結果:

再運行一次:

##總結:

通過上述例子可以發現:

隨機數是種子經過計算產生的。

  • 不含參的建構函式每次都使用目前時間作為種子,隨機性更強
  • 而含參的建構函式其實是偽隨機,更有可預見性

Java Random 含參與不含參建構函式的區別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.