1. 簡(jiǎn)介
Random 有兩個(gè)構(gòu)造方法:
public Random()
public Random(long seed)
其實(shí)第一個(gè)無參構(gòu)造方法會(huì)默認(rèn)以當(dāng)前時(shí)間作為種子川蒙。那么什么是種子呢?
先來看看 Random 的 next() 方法:
protected int next(int bits) {
long oldseed, nextseed;
AtomicLong seed = this.seed;
do {
oldseed = seed.get();
nextseed = (oldseed * multiplier + addend) & mask;
} while (!seed.compareAndSet(oldseed, nextseed));
return (int)(nextseed >>> (48 - bits));
}
seed 就是種子恳邀,它的作用就是用于生成一個(gè)隨機(jī)數(shù)。
2. 兩個(gè)構(gòu)造方法有什么不同?
現(xiàn)在看一個(gè)例子夸浅,對(duì)比這兩個(gè)構(gòu)造方法有什么不同。
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 無參的構(gòu)造方法扔役,運(yùn)行結(jié)果如下:
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
可以看出每次的結(jié)果都不一樣帆喇。下面使用 Random 的有參構(gòu)造方法:
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("");
}
}
}
打印結(jié)果如下:
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
這是因?yàn)闊o參的構(gòu)造方法是以當(dāng)前時(shí)間作為種子,每次的種子都不一樣亿胸,隨機(jī)性更強(qiáng)坯钦。而有參的構(gòu)造方法是以固定值作為種子,每次輸出的值都是一樣的侈玄。