public class Demo14 {
public static void main(String[] args){
//創建隨機數對象
Random r = new Random();
//創建集合對象
HashSet<Integer> it = new HashSet<>();
//判斷長度是否小於10,在范圍內就把隨機數添加到集合中去
while(it.size()<10){
int num = r.nextInt(20)+1;
it.add(num);
}
//遍歷集合
for (Integer x: it){
System.out.println(x);
}
}
}
輸出結果:
1
2
19
5
7
8
10
12
13
15