我有一个国家的数组列表。我想从中随机选择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));