Jslfl【软件开发技术笔记】

java生成不重复随机数

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
/**
     * 生成指定位数不重复的随机数字,一般用于生成验证码
     * @param length
     * @return
     */

public static String generateRandomNum(int length){
    if(length < 1 || length > 10)
        throw new IllegalArgumentException("参数length必须大于 0 且小于 11");
       
    int[] array = {0,1,2,3,4,5,6,7,8,9};
    Random rand = new Random();
    for (int i = 10; i > 1; i--) {
        int index = rand.nextInt(i);
        int tmp = array[index];
        array[index] = array[i - 1];
        array[i - 1] = tmp;
    }
    //第一个元素不能为0,不然生成后会少位数
    if(array[0] == 0){
        array[0] = array[1];
        array[1] = 0;
    }
       
    long result = 0;
    for(int i = 0; i < length; i++)
        result = result * 10 + array[i];
       
    return String.valueOf(result);
}

Comments are currently closed.