Random類
java.util.Random類用於產生隨機數。需要導入包:
import java.util.Random;
方法 | 解釋 |
---|---|
Random() | 創建一個Random類對象 |
Random(long seed) | 使用seed作為隨機種子創建一個Random類對象 |
int nextInt() | 下一個整型值 |
int nextInt(int bound) | 0~bound-1之間的隨機整數 |
long nextLong() | 下一個長整型值 |
float nextFloat() | 0.0到1.0之間的下一個浮點值 |
double nextDouble() | 0.0到1.0之間的下一個雙精度值 |
r.nextInt():產生整數范圍的隨機數(均勻分布)
import java.util.Random;
public class TestRadomNextInt {
// int 值
public static void main(String[] args) {
Random r = new Random();
for (int i = 1; i <= 10; i++) {
int num = r.nextInt();
System.out.println(num);
}
}
}
56845052
-686301646
-1233789074
1636415628
1894696653
-595067037
-1041962125
392105380
-226429564
116890454
nextInt(int bound):隨機生成[0,bound)之間的整數。注意是左開右閉區間,可能取到0,不能取到bound的值。
bound:邊界
import java.util.Random;
public class TestRadomNextInt {
public static void main(String[] args) {
Random r = new Random();
for (int i = 1; i <= 10; i++) {
int num = r.nextInt(10);
System.out.println(num);
}
}
}
應用示例:生成10~20之間的隨機數:
(1)范圍:20-10=10,即隨機數范圍跨度為10,
r.nextInt(11)可以滿足:[0——11)即[0——10]
(2)從10開始,則整體+10,即r.nextInt(11) + 10
import java.util.Random;
public class TestRandomRange {
public static void main(String[] args) {
Random r = new Random();
for (int i = 0; i < 100; i++) {
int n = r.nextInt(11) + 10;
System.out.println(n);
}
}
}
歸納:生成a~b之間的隨機數,只需要使用 r.nextInt(b-a+1)+a即可。
種子:Random(long seed)
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
public class TestRadom {
public static void main(String[] args) {
無參隨機數();
無參隨機數();
帶種子隨機數();
帶種子隨機數();
}
static void 無參隨機數() {
Random r = new Random();
for (int i = 0; i < 10; i++) {
System.out.print(r.nextInt(101) + "\t");// 0-100的隨機整數
}
System.out.println();
}
static void 帶種子隨機數() {
Random r2 = new Random(100);
for (int i = 0; i < 10; i++) {
System.out.print(r2.nextInt(101) + " ");// 0-100的隨機整數
}
System.out.println();
}
}
運行結果:
59 41 10 41 4 80 7 69 32 91
57 54 67 25 52 4 3 100 23 75
92 94 52 24 1 74 60 55 56 4
92 94 52 24 1 74 60 55 56 4
↑通過運行結果可以發現,種子相同的情況下,生成的隨機數其實是一樣的——組內看似隨機,但多次運行結果相同。
事實上,Random的無參構造方法中,使用了時間作為種子,源碼如下:
public Random() {
this(seedUniquifier() ^ System.nanoTime());
}
Java 7中,對Random類進行了升級,提供了ThreadLocalRandom類,在並發訪問環境下,可以減少多線程的資源競爭,提升線程的安全性。
Random r = new Random();
↓
ThreadLocalRandom r = ThreadLocalRandom.current();