1
我有這個空的數組列表。 我想添加6個隨機生成的整數(1到6),但我不希望它被複制。 不知何故,我無法設法爲此創建循環。 我不斷得到重複的值,甚至數組列表的大小不斷變化。 這是我的代碼。 在此先感謝。如何將隨機整數添加到ArrayList而不會重複
ArrayList al = new ArrayList();
int rnd = new Random().nextInt(6)+1;
while(!(al.contains(rnd))){
for(int i=0; i<=5; i++){
al.add(rnd);
rnd = new Random().nextInt(6)+1;
}
rnd = new Random().nextInt(6)+1;
}
System.out.print(al);
看一看的。載有()的'ArrayList'的方法。 – smsnheck
爲什麼不使用'Set'?其中不允許重複 –
添加到'Set',然後轉換爲'ArrayList'。 – Maroun