【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 shusheng@yiji.com
 * @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);
        }
    }

}
终身学习者
原文地址:https://www.cnblogs.com/zuixinxian/p/10340911.html