搜索
您的当前位置:首页正文

Random 种子的作用

来源:二三娱乐

1. 简介

Random 有两个构造方法:

public Random()
public Random(long seed)

其实第一个无参构造方法会默认以当前时间作为种子。那么什么是种子呢?

先来看看 Random 的 next() 方法:

protected int next(int bits) {
    long oldseed, nextseed;
    AtomicLong seed = this.seed;
    do {
        oldseed = seed.get();
        nextseed = (oldseed * multiplier + addend) & mask;
    } while  nextseed));
    return (int)(nextseed >>> (48 - bits));
}

seed 就是种子,它的作用就是用于生成一个随机数。

2. 两个构造方法有什么不同?

现在看一个例子,对比这两个构造方法有什么不同。

public class RandomDemo {

    public static void main(String[] args) {
        for(int i = 0; i < 5; i++) {
            Random random = new Random();
            for(int j = 0; j < 5; j++) {
                System.out.print(" " + random.nextInt(10) + ", ");
            }
            System.out.println("");
        }
    }
    
}

以上使用了 Random 无参的构造方法,运行结果如下:

2 0 3 2 5 
6 4 1 9 7 
9 1 8 3 6 
2 5 3 5 6 
9 9 9 4 5 

可以看出每次的结果都不一样。下面使用 Random 的有参构造方法:

public class RandomDemo {

    public static void main(String[] args) {
        for(int i = 0; i < 5; i++) {
            Random random = new Random(47);
            for(int j = 0; j < 5; j++) {
                System.out.print( + random.nextInt(10) + " ");
            }
            System.out.println("");
        }
    }
    
}

打印结果如下:

8 5 3 1 1 
8 5 3 1 1 
8 5 3 1 1 
8 5 3 1 1 
8 5 3 1 1 

这是因为无参的构造方法是以当前时间作为种子,每次的种子都不一样,随机性更强。而有参的构造方法是以固定值作为种子,每次输出的值都是一样的。

Top