废话不多说,直接上代码
public static void main(String[] args) {
ArrayList word = new ArrayList();
Random random = new Random();
//用变量i控制循环次数
int i = 0;
while (i<5){//i小于5,则生成5个不重复的随机数
int i1 = random.nextInt(10);
if (word.contains(i1)){
//用contains来判断集合中是否存在生成的随机数,存在则继续循环生成新的随机数;
continue;
}else {
//当不存在生成的随机数,就向集合中添加这个随机数,i也自增1
word.add(i1);
i++;
}
}
//遍历打印
for (Object a:word){
System.out.println("a = " + a);
}
}