从数组中选择随机元素,但是唯一
我有一系列国家。 我想从我的数组列表中选择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));
对arrays进行随机播放,然后对前5个元素进行切片。
这将保证5个独特的随机元素。