一、Java隨機數的產生方式
在Java中,隨機數的概念從廣義上將,有三種。
1、通過System.currentTimeMillis()來獲取一個當前時間毫秒數的long型數字。
2、通過Math.random()返回一個0到1之間的double值。
3、通過Random類來產生一個隨機數,這個是專業的Random工具類,功能強大。
二、Random類API說明
1、Java API說明
Random類的實例用于生成偽隨機數流。此類使用 48 位的種子,使用線性同余公式對其進行修改(請參閱 Donald Knuth 的《The Art of Computer Programming, Volume 2》,第 3.2.1 節)。
如果用相同的種子創建兩個 Random 實例,則對每個實例進行相同的方法調用序列,它們將生成并返回相同的數字序列。為了保證屬性的實現,為類 Random 指定了特定的算法。
很多應用程序會發現 Math 類中的 random 方法更易于使用。
2、方法摘要
Random()
創建一個新的隨機數生成器。
Random(long seed)
使用單個 long 種子創建一個新隨機數生成器:
public Random(long seed) { setSeed(seed); } next 方法使用它來保存隨機數生成器的狀態。
protected int next(int bits)
生成下一個偽隨機數。
boolean nextBoolean()
返回下一個偽隨機數,它是從此隨機數生成器的序列中取出的、均勻分布的 boolean 值。
void nextBytes(byte[] bytes)
生成隨機字節并將其置于用戶提供的字節數組中。
double nextDouble()
返回下一個偽隨機數,它是從此隨機數生成器的序列中取出的、在 0.0 和 1.0之間均勻分布的 double 值。
float nextFloat()
返回下一個偽隨機數,它是從此隨機數生成器的序列中取出的、在 0.0 和 1.0 之間均勻分布的 float 值。
double nextGaussian()
返回下一個偽隨機數,它是從此隨機數生成器的序列中取出的、呈高斯(“正常地”)分布的 double 值,其平均值是 0.0,標準偏差是 1.0。
int nextInt()
返回下一個偽隨機數,它是此隨機數生成器的序列中均勻分布的 int 值。
int nextInt(int n)
返回一個偽隨機數,它是從此隨機數生成器的序列中取出的、在 0(包括)和指定值(不包括)之間均勻分布的 int值。
long nextLong()
返回下一個偽隨機數,它是從此隨機數生成器的序列中取出的、均勻分布的 long 值。
void setSeed(long seed)
使用單個 long 種子設置此隨機數生成器的種子。
三、Random類使用說明
1、帶種子與不帶種子的區別
Random類使用的根本是策略分帶種子和不帶種子的Random的實例。
通俗說,兩者的區別是:
帶種子的,每次運行生成的結果都是一樣的。
不帶種子的,每次運行生成的都是隨機的,沒有規律可言。
2、創建不帶種子的Random對象
Random random = new Random();
3、創建不帶種子的Random對象
有兩種方法:
1) Random random = new Random(555L);
2) Random random = new Random();
random.setSeed(555L);
四、綜合應用
下面通過最近寫的一個隨機數工具類來展示用法:
import java.util.Random;
/**
* 隨機數、隨即字符串工具
* User: leizhimin
* Date: 2008-11-19 9:43:09
*/
public class RandomUtils {
public static final String allChar = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static final String letterChar = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static final String numberChar = "0123456789";
/**
* 返回一個定長的隨機字符串(只包含大小寫字母、數字)
*
* @param length 隨機字符串長度
* @return 隨機字符串
*/
public static String generateString(int length) {
StringBuffer sb = new StringBuffer();
Random random = new Random();
for (int i = 0; i < length; i++) {
sb.append(allChar.charAt(random.nextInt(allChar.length())));
}
return sb.toString();
}
/**
* 返回一個定長的隨機純字母字符串(只包含大小寫字母)
*
* @param length 隨機字符串長度
* @return 隨機字符串
*/
public static String generateMixString(int length) {
StringBuffer sb = new StringBuffer();
Random random = new Random();
for (int i = 0; i < length; i++) {
sb.append(allChar.charAt(random.nextInt(letterChar.length())));
}
return sb.toString();
}
/**
* 返回一個定長的隨機純大寫字母字符串(只包含大小寫字母)
*
* @param length 隨機字符串長度
* @return 隨機字符串
*/
public static String generateLowerString(int length) {
return generateMixString(length).toLowerCase();
}
/**
* 返回一個定長的隨機純小寫字母字符串(只包含大小寫字母)
*
* @param length 隨機字符串長度
* @return 隨機字符串
*/
public static String generateUpperString(int length) {
return generateMixString(length).toUpperCase();
}
/**
* 生成一個定長的純0字符串
*
* @param length 字符串長度
* @return 純0字符串
*/
public static String generateZeroString(int length) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
sb.append('0');
}
return sb.toString();
}
/**
* 根據數字生成一個定長的字符串,長度不夠前面補0
*
* @param num 數字
* @param fixdlenth 字符串長度
* @return 定長的字符串
*/
public static String toFixdLengthString(long num, int fixdlenth) {
StringBuffer sb = new StringBuffer();
String strNum = String.valueOf(num);
if (fixdlenth - strNum.length() >= 0) {
sb.append(generateZeroString(fixdlenth - strNum.length()));
} else {
throw new RuntimeException( "將數字" + num + "轉化為長度為" + fixdlenth + "的字符串發生異常!");
}
sb.append(strNum);
return sb.toString();
}
/**
* 根據數字生成一個定長的字符串,長度不夠前面補0
*
* @param num 數字
* @param fixdlenth 字符串長度
* @return 定長的字符串
*/
public static String toFixdLengthString(int num, int fixdlenth) {
StringBuffer sb = new StringBuffer();
String strNum = String.valueOf(num);
if (fixdlenth - strNum.length() >= 0) {
sb.append(generateZeroString(fixdlenth - strNum.length()));
} else {
throw new RuntimeException( "將數字" + num + "轉化為長度為" + fixdlenth + "的字符串發生異常!");
}
sb.append(strNum);
return sb.toString();
}
public static void main(String[] args) {
System.out.println(generateString(15));
System.out.println(generateMixString(15));
System.out.println(generateLowerString(15));
System.out.println(generateUpperString(15));
System.out.println(generateZeroString(15));
System.out.println(toFixdLengthString(123, 15));
System.out.println(toFixdLengthString(123L, 15));
}
}
運行結果:
vWMBPiNbzfGCpHG
23hyraHdJkKPwMv
tigowetbwkm1nde
BPZ1KNEJPHB115N
000000000000000
000000000000123
000000000000123
Process finished with exit code 0
六、總結
1、隨機數很常用,在Java有三種產生方式,以Random隨機數的使用最為復雜。
2、Random類對象有是否帶種子之分,帶種子的只要種子相同,多次運行,生成隨機數的結果總是那樣。
3、帶種子隨機數的帶種子的對象創建方式有兩種,效果一樣。但是帶種子的隨機數用處似乎不大。
4、Random的功能涵蓋了Math.random()的功能。
5、可以通過隨機數去做實現隨機字符串等復雜的隨機數據。
6、不要研究不重復的隨機數,意義不大
補充代碼:
package com.test;
import java.util.Random;
public class RandomUtils {
public static final String ALLCHAR = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static final String LETTERCHAR = "abcdefghijkllmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static final String NUMBERCHAR = "0123456789";
/**
* 返回一個定長的隨機字符串(只包含大小寫字母、數字)
* @param length 隨機字符串長度
* @return 隨機字符串
*/
public static String generateString(int length)
{
StringBuffer sb = new StringBuffer();
Random random = new Random();
for (int i = 0; i < length; i++) {
sb.append(ALLCHAR.charAt(random.nextInt(ALLCHAR.length())));
}
return sb.toString();
}
/**
* 返回一個定長的隨機純字母字符串(只包含大小寫字母)
* @param length 隨機字符串長度
* @return 隨機字符串
*/
public static String generateMixString(int length)
{
StringBuffer sb = new StringBuffer();
Random random = new Random();
for (int i = 0; i < length; i++)
{
sb.append(ALLCHAR.charAt(random.nextInt(LETTERCHAR.length())));
}
return sb.toString();
}
/**
* 返回一個定長的隨機純大寫字母字符串(只包含大小寫字母)
*
* @param length 隨機字符串長度
* @return 隨機字符串
*/
public static String generateLowerString(int length) {
return generateMixString(length).toLowerCase();
}
/**
* 返回一個定長的隨機純小寫字母字符串(只包含大小寫字母)
*
* @param length 隨機字符串長度
* @return 隨機字符串
*/
public static String generateUpperString(int length) {
return generateMixString(length).toUpperCase();
}
/**
* 生成一個定長的純0字符串
*
* @param length 字符串長度
* @return 純0字符串
*/
public static String generateZeroString(int length) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
sb.append('0');
}
return sb.toString();
}
/**
* 根據數字生成一個定長的字符串,長度不夠前面補0
*
* @param num 數字
* @param fixdlenth 字符串長度
* @return 定長的字符串
*/
public static String toFixdLengthString(long num, int fixdlenth) {
StringBuffer sb = new StringBuffer();
String strNum = String.valueOf(num);
if (fixdlenth - strNum.length() >= 0) {
sb.append(generateZeroString(fixdlenth - strNum.length()));
} else {
throw new RuntimeException("將數字" + num + "轉化為長度為" + fixdlenth + "的字符串發生異常!");
}
sb.append(strNum);
return sb.toString();
}
/**
* 根據數字生成一個定長的字符串,長度不夠前面補0
*
* @param num 數字
* @param fixdlenth 字符串長度
* @return 定長的字符串
*/
public static String toFixdLengthString(int num, int fixdlenth) {
StringBuffer sb = new StringBuffer();
String strNum = String.valueOf(num);
if (fixdlenth - strNum.length() >= 0) {
sb.append(generateZeroString(fixdlenth - strNum.length()));
} else {
throw new RuntimeException("將數字" + num + "轉化為長度為" + fixdlenth + "的字符串發生異常!");
}
sb.append(strNum);
return sb.toString();
}
/**
* 每次生成的len位數都不相同
* @param param
* @return 定長的數字
*/
public static int getNotSimple(int[] param,int len)
{
Random rand = new Random();
for (int i = param.length; i > 1; i--)
{
int index = rand.nextInt(i);
int tmp = param[index];
param[index] = param[i - 1];
param[i - 1] = tmp;
}
int result = 0;
for(int i = 0; i < len; i++)
{
result = result * 10 + param[i];
}
return result;
}
public static void main(String[] args) {
System.out.println(generateString(10));
System.out.println(generateMixString(10));
System.out.println(generateLowerString(10));
System.out.println(generateUpperString(10));
System.out.println(generateZeroString(10));
System.out.println(toFixdLengthString(123, 10));
System.out.println(toFixdLengthString(123L, 10));
int[] in = {1,2,3,4,5,6,7};
System.out.println(getNotSimple(in,3));
}
}