直接上代码,需要用到的直接copy,代码上有注释,简单易懂,拿走不谢!
package com.jglz.qing.random;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class RandomTest {
public static void main(String[] args) {
List<Integer> numberList = getQuestionNumList(10);
List<Integer> numberList2 = getRandomQuestionNumList(10, 10);
System.out.println(numberList.toString());
System.out.println(numberList2.toString());
}
/**
* 得到[0,questionCount)之间的共questionCount个不重复的随机数
*/
public static List<Integer> getQuestionNumList(int questionCount) {
List<Integer> myList = new ArrayList<Integer>(); // 生成数据集,用来保存随即生成数,并用于判断
Random rd = new Random();
while (myList.size() < questionCount) {
int num = rd.nextInt(questionCount);// nextInt(n)将返回一个大于等于0小于n的随机数
if (!myList.contains(num)) {
myList.add(num);
}
}
return myList;
}
/**
* 得到[0,totalCount)之间的questionCount个不重复的随机数 。
* totalCount必须大于等于questionCount
*/
public static List<Integer> getRandomQuestionNumList(int questionCount,
int totalCount) {
if (totalCount < questionCount) {
return null;
} else {
List<Integer> myList = new ArrayList<Integer>(); // 生成数据集,用来保存随即生成数,并用于判断
Random rd = new Random();
while (myList.size() < questionCount) {
// int num = rd.nextInt(totalCount);
// 如果上面的代码变成下面这样,将得到[10,totalCount+10)之间的questionCount个不重复的随机数
int num = rd.nextInt(totalCount) + 10;
if (!myList.contains(num)) {
myList.add(num);
}
}
return myList;
}
}
}
附上我执行出来的结果截图:
每个人运行出来的结果都不相同哦,因为是随机数嘛~~~