我有一系列国家。我想从我的数组列表中选择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,country 2等相同...所以我希望它们总是不同。
解决方案:
Collections.shuffle(Arrays.asList(allCountries));
答案 0 :(得分:19)
对阵列进行随机播放,然后对前5个元素进行切片。
这将保证5个独特的随机元素。