现在的位置: 首页 > 综合 > 正文

Java生成不重复的随机数

2013年03月26日 ⁄ 综合 ⁄ 共 1216字 ⁄ 字号 评论关闭

转载:http://blog.csdn.net/wuxianglong/article/details/5775796

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class UnSeqRandomNumber {
    private int min;
    private int max;
    public UnSeqRandomNumber() {
        this.min = 0;
        this.max = 10; 
    } 
    public UnSeqRandomNumber(int min, int max) {
        this();
        if (max > min) {
            this.min = min;
            this.max = max; 
        } else 
            System.out.println("max比min小,按默认的值生成UnrepeatRandomMumber对象!");
    }
    // 第一种方法:排除法.随机生成数字,如果是新生成的数字则放到结果集中
    // 否则不采取行动
    public Integer[] getRandomA(int length) {
        if (length <= 0) {
            System.out.println("数字长度小");
            return new Integer[0];
        } else if (length > (this.max - this.min)) {
            System.out.println("结果列表长度达不到要求:" + length + "结果只能是:"  + (this.max - this.min));
            length = this.max - this.min;
        }
        Random rand = new Random();
        List<Integer> list = new ArrayList<Integer>();
        while (list.size() < length) {
            Integer randnum = new Integer(this.min + rand.nextInt(this.max - this.min + 1));
            if (!list.contains(randnum)) {
                list.add(randnum);
            }
        }
        return (Integer[]) list.toArray(new Integer[0]);
    }
    public static void outputArray(Integer[] array) {
        if (array != null) {
            for (int i = 0; i < array.length; i++) {
                System.out.println(array[i] + " ");
            }
        }
        System.out.println();
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        UnSeqRandomNumber test = new UnSeqRandomNumber(5, 35);
        outputArray(test.getRandomA(100));
    }
}

抱歉!评论已关闭.