Random同じシードが同じシーケンスを生成

1431 ワード

    public void test_shuffff() {
        List<String> list = Lists.newArrayList( "7451880340:10138652","7451880338:10138652","7451862057:10138652","7451862249:10138652","7451862316:10138652");
        Collections.shuffle(list,new Random(10));
        System.out.println(list);
    }

ふと気づく
Collections.shuffle(List,Random)
の時、何度も実行した結果はすべて一致して、shuffleのソースコードの中を見ます
            // Shuffle array
            for (int i=size; i>1; i--)
                swap(arr, i-1, rnd.nextInt(i));

どうしてもランダムなはずだ!
半日探してみたら、Randomクラスの説明:
If two instances of {@code Random} are created with the same * seed, and the same sequence of method calls is made for each, they * will generate and return identical sequences of numbers
つまり、Randomインスタンスのシードが同じである場合、同じメソッドの実行結果は同じです.例:
    public static void main(String[] args) {
        Random rd = new Random(10);
        System.out.println(rd.nextInt(1));
        System.out.println(rd.nextInt(3));
        System.out.println(rd.nextInt(4));
        System.out.println(rd.nextInt(8));
    }

複数回の印刷結果は一致しています.
参照
0
0
1
3
シードを指定しないRandomとの違いに注意してください.デフォルトのRandom()は現在のシステム時間をシードとしており、実行するたびに自然に異なります.