需求: 获得十个1-20的随机数,要求随机数不能重复,存储到集合中并遍历
分析:
1.创建Set集合对象,可以使用 HashSet 也可以使用 TreeSet ,区别在于TreeSet是排序后的 2.创建随机数对象,获取一个随机数 3.判断集合长度是否大于10,是停止生成、存储并遍历 否:继续生成直到长度大于10停止生成、存储并遍历 4.输出代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public class SetDemo { public static void main(String[] args) { //创建Set集合对像 Set<Integer> s= new TreeSet<Integer>(); //创建随机数对象 Random r= new Random(); while (s.size()< 10 ){ int num= r.nextInt( 20 )+ 1 ; s.add(num); } for (Integer i:s){ System.out.println(i); } } } ? |
补充:
通过单个数组简易实现不重复随机数生成,先上源码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
/** * 获取随机数组 * @param 源数组 * @param size 目标数组大小 * @return 随机数组 */ public static int [] getRandomRes( int [] source, int size){ if (source == null && size > source.length) { return ; } int [] result = new int [size]; Random random = new Random(); for ( int i = 0 ; i < size; i++) { int randomIndex = random.nextInt(source.length - 1 - i); int randomRes = source[randomIndex]; result[i] = randomRes; int temp = source[randomIndex]; source[randomIndex] = source[source.length - 1 - i]; source[source.length - 1 - i] = temp; } return result; } |
下面看图解,数字为数组的index。
黑色数字表示能随机到的数,红色代表不能随机到数。
因此只能随机到index:0~4的数,假设是2,然后将2与index5互换位置。
此时结果 result[] = {2}
继续循环
从前index:0~3中循环,假设取出 index0 ,与 index4 互换,此时结果为 result = {2,0} ,依次类推。
优点: 简单快捷
缺点: 每次无法取到最后一个数。
不断随机,使用Set去重
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
/** *生成随机数组 *@param size 目标数组大小 *@param max 目标数最大值 */ public Set<Integer> getRandomSet( int size, int max){ Random random= new Random(); Set<Integer> result= new LinkedHashSet<Integer>(); while (generated.size() < size) { Integer next = rng.nextInt(max) + 1 ; generated.add(next); } } |
此处使用 LinkedHashSet 保证插入顺序与结果相同。
到此这篇关于Java案例实现不重复的随机数的文章就介绍到这了,更多相关Java不重复随机数内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
原文链接:https://HdhCmsTestcnblogs测试数据/CYan521/p/16073382.html