随机数的产生在一些代码中很常用,也是我们必须要掌握的。而Java中产生随机数的方法主要有三种:

第一种:new Random()

第二种:Math.random()

第三种:currentTimeMillis()

个人比较推荐第一种。第二种次推荐。第三种不推荐。

new Random()

第一种需要借助java.util.Random类来产生一个随机数发生器,也是最常用的一种,构造函数有两个,Random()和Random(long seed)。第一个就是以当前时间为默认种子,第二个是以指定的种子值进行。产生之后,借助不同的语句产生不同类型的数。

种子就是产生随机数的第一次使用值,机制是通过一个函数,将这个种子的值转化为随机数空间中的某一个点上,并且产生的随机数均匀的散布在空间中。以后产生的随机数都与前一个随机数有关。

1
2
3
4
5
private int getRandom() {
Random r = new Random(1);
int rand = r.nextInt(100);
return rand;
}

nextInt() 表示随机生成一个 [0, Integer.MAX_VALUE - 1] 的数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public int nextInt() {
return next(32);
}
/**
* Generates the next pseudorandom number. Subclasses should
* override this, as this is used by all other methods.
*
* <p>The general contract of {@code next} is that it returns an
* {@code int} value and if the argument {@code bits} is between
* {@code 1} and {@code 32} (inclusive), then that many low-order
* bits of the returned value will be (approximately) independently
* chosen bit values, each of which is (approximately) equally
* likely to be {@code 0} or {@code 1}. The method {@code next} is
* implemented by class {@code Random} by atomically updating the seed to
* <pre>{@code (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1)}</pre>
* and returning
* <pre>{@code (int)(seed >>> (48 - bits))}.</pre>
*
* This is a linear congruential pseudorandom number generator, as
* defined by D. H. Lehmer and described by Donald E. Knuth in
* <i>The Art of Computer Programming,</i> Volume 2:
* <i>Seminumerical Algorithms</i>, section 3.2.1.
*
* @param bits random bits
* @return the next pseudorandom value from this random number
* generator's sequence
* @since 1.1
*/
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));
}

nextInt(bound) : 返回 [0, bound - 1 ] 之间的随机数。

除了 int 之外,还可以获取 double,boolean, long, 正态分布的值等。

Math.random()

第二种方法返回的数值是 [ 0.0, 1.0 )的double型数值,由于double类数的精度很高,可以在一定程度下看做随机数,借助(int)来进行类型转换就可以得到整数随机数了。

1
2
3
4
5
private int getRandom() {
int max = 100, min = 1;
int ran2 = (int) (Math.random() * (max - min) + min);
return ran2;
}

currentTimeMillis()

至于第三种方法虽然不常用,但是也是一种思路。方法返回从1970年1月1日0时0分0秒(这与UNIX系统有关)到现在的一个long型的毫秒数,取模之后即可得到所需范围内的随机数。

1
2
3
4
5
6
private int getRandom() {
int max = 100, min = 1;
long randomNum = System.currentTimeMillis();
int ran3 = (int) (randomNum % (max - min) + min);
return ran3;
}

参考