方法1
public class Test {
public static void main(String[] args) {
// 获得测试结果
List<Integer> list = getNoRepeatRandomList(2, 32, 5);
// 遍历测试结果
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i));
if (i < list.size() - 1) {
System.out.print(",");
}
}
}
/**
* 从一个范围中取出n个不重复的随机数
*
* @param start 范围开始值
* @param end 范围结束值
* @param n 取出的随机数数目
* @return 不重复的随机数集合
*/
private static List<Integer> getNoRepeatRandomList(Integer start, Integer end, Integer n) {
// 如果需要的随机数大于全部的随机数总量,那么将抛出异常
if (n > (end - start + 1)) throw new RuntimeException("需要的随机数大于全部的随机数总量");
// 所有随机数列表
List<Integer> randomList = new ArrayList<>();
// 最终返回的随机数列表
List<Integer> resultList = new ArrayList<>();
// 将随机数放入随机数列表中
for (int i = start; i <= end; i++) {
randomList.add(i);
}
// 获取固定数量的随机数
while (resultList.size() < n) {
// 随机数的下标
int index = (int) (Math.random() * randomList.size());
// 将随机数放在返回值集合中
resultList.add(randomList.get(index));
// 移除随机数集合中的随机数(该随机数已经被选中了,所以下次不能在选它了)
randomList.remove(index);
}
return resultList;
}
}
方法2
public class Test {
public static void main(String[] args) {
// 获得测试结果
List<Integer> list = getNoRepeatRandomList(2, 32, 25);
// 遍历测试结果
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i));
if (i < list.size() - 1) {
System.out.print(",");
}
}
}
/**
* 从一个范围中取出n个不重复的随机数
*
* @param start 范围开始值
* @param end 范围结束值
* @param n 取出的随机数数目
* @return 不重复的随机数集合
*/
private static List<Integer> getNoRepeatRandomList(Integer start, Integer end, Integer n) {
// 如果需要的随机数大于全部的随机数总量,那么将抛出异常
if (n > (end - start + 1)) throw new RuntimeException("需要的随机数大于全部的随机数总量");
// 创建没有重复数据的set集合
Set<Integer> set = new HashSet<>();
while (set.size() < n) {
// 将随机数添加到set集合中
set.add((int) (Math.random() * (end + 1)) + start);
}
// 返回集合,其中将set集合转换为list集合的原因是因为方便以后使用
return new ArrayList<>(set);
}
}
如果你不想使用Math.random()
,还可以使用Random对象
,那么getNoRepeatRandomList()
方法可以这样写,如下:
private static List<Integer> getNoRepeatRandomList(Integer start, Integer end, Integer n) {
// 如果需要的随机数大于全部的随机数总量,那么将抛出异常
if (n > (end - start + 1)) throw new RuntimeException("需要的随机数大于全部的随机数总量");
// 随机数对象
Random random = new Random();
// 创建没有重复数据的set集合
Set<Integer> set = new HashSet<>();
while (set.size() < n) {
// 将随机数添加到set集合中
set.add(random.nextInt(end + 1) + start);
}
// 返回集合,其中将set集合转换为list集合的原因是因为方便以后使用
return new ArrayList<>(set);
}
总结
大家可能感觉方法1
写的代码有点多,可能会想为什么要用它,毕竟方法2
中set集合的元素不会重复,并且代码比较少,但是我想说当N值比较小的时候set集合还是可以的,如果说N值比较大呢,比如在2~32个随机数中找出30个不重复数字,如果还使用set集合,那么中间添加失败的概率会很高,所以N值很大的时候set集合效率并不高,在方法1
中我使用的是将所有随机数值放入list集合,然后找出来一个就删除一个,这样可以保证取出来的数字都不会重复,虽然代码量多一点,但是效率也更高