HashSet:获取10个1至20的随机数,要求随机数不能重复

Posted zuixinxian

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HashSet:获取10个1至20的随机数,要求随机数不能重复相关的知识,希望对你有一定的参考价值。

package com.yjf.esupplier.common.test;

import java.util.HashSet;
import java.util.Random;

/**
 * @author shusheng
 * @description 获取10个1至20的随机数,要求随机数不能重复
 * @Email [email protected]
 * @date 2018/12/17 15:33
 */
public class HashSetDemo {

    public static void main(String[] args) {
        // 创建随机数对象
        Random r = new Random();

        // 创建一个Set集合
        HashSet<Integer> ts = new HashSet<Integer>();

        // 判断集合的长度是不是小于10
        while (ts.size() < 10) {
            int num = r.nextInt(20) + 1;
            ts.add(num);
        }

        // 遍历Set集合
        for (Integer i : ts) {
            System.out.println(i);
        }
    }

}

 

以上是关于HashSet:获取10个1至20的随机数,要求随机数不能重复的主要内容,如果未能解决你的问题,请参考以下文章