Java 得到n个小于n的随机数list

直接上代码,需要用到的直接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;
		}
	}
}

附上我执行出来的结果截图:


每个人运行出来的结果都不相同哦,因为是随机数嘛~~~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值