2011-07-18 49 views
8

我有一些國家。我想從我的數組列表中選擇5個隨機國家,但我希望它們是唯一的。 這是我到目前爲止有:從數組中挑選隨機元素,但唯一

String allCountries[] = {"Finland", "Latvia", "Poland", "Afghanistan", "Albania", "Algeria"}; 

String country1 = (allCountries[new Random().nextInt(allCountries.length)]); 
String country2 = (allCountries[new Random().nextInt(allCountries.length)]); 
String country3 = (allCountries[new Random().nextInt(allCountries.length)]); 
String country4 = (allCountries[new Random().nextInt(allCountries.length)]); 
String country5 = (allCountries[new Random().nextInt(allCountries.length)]); 

什麼是同時生成隨機元素來比較這些字符串的最好方法?

編輯:

我表示自己不好。我遇到的問題是我不希望字符串country1,country2等相同......所以我希望它們總是與衆不同。

解決方案:

Collections.shuffle(Arrays.asList(allCountries)); 
+3

你**不要**要他們是唯一的?如果是這樣,你爲什麼需要比較它們,你有什麼應該工作得很好。 –

+0

您的標題和問題有衝突。你或你不想要獨特? – Perception

+0

你不這樣做嗎?請澄清矛盾的標題。 – adarshr

回答

18

洗牌陣列和然後切片第一5個元素。

這將保證5個獨特的隨機元素。

+1

絕妙的主意......我也將代碼添加到了我的問題中。謝謝 :) –