需求:获得十个1-20的随机数,要求随机数不能重复,存储到集合中并遍历
分析:
1.创建Set集合对象,可以使用HashSet也可以使用TreeSet,区别在于TreeSet是排序后的
2.创建随机数对象,获取一个随机数
3.判断集合长度是否大于10,是停止生成、存储并遍历
否:继续生成直到长度大于10停止生成、存储并遍历
4.输出
代码
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);
}
}
}