1. 第一种
/**
* 随机生成不重复的随机数
* @param min 最小值
* @param max 最大值
* @param size 个数
* @return
*/
public static List<Integer> getRandom(int min,int max,int size){
List<Integer> nums = null;
if (size>(max-min) || size==0 || min>=max){
return nums;
}
nums = new ArrayList<Integer>();
Random random = new Random();
int code;
A:for (;;) {
code = (random.nextInt(max)+min);
for (int c : nums){
if (c==code){
continue A;
}
}
nums.add(code);
if (nums.size()==size) {
break;
}
}
return nums;
}
2.第二种
/**
* 获取指定范围内指定个数的随机不重复数组
* @param min
* @param max
* @param n
* @return
*/
public static int[] randomNum(int min, int max, int n){
Set<Integer> set = new HashSet<Integer>();
int[] result = new int[n];
for (; true;) {
// 调用Math.random()方法
Double rd = Math.random()*1000.0 ;
int vl = rd.intValue()%n+min ;
if (vl> max || vl<min)
continue;
// 将不同的数存入HashSet中
set.add(vl);
// 如果存入的数小于指定生成的个数,则调用递归再生成剩余个数的随机数,如此循环,直到达到指定大小
if (set.size() >= n) {
break;
}
}
int i = 0;
for (int a : set) {
result[i] = a;
i++;
}
return result;
}