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); } } }