从数组中选择随机元素,但是唯一

Bad*_*ari 9 java arrays

我有一系列国家.我想从我的数组列表中选择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)]);
Run Code Online (Sandbox Code Playgroud)

在生成随机元素时比较这些字符串的最佳方法是什么?

编辑:

我表达自己很糟糕.我遇到的问题是我不希望字符串country1,country 2等相同...所以我希望它们总是不同的.

解:

Collections.shuffle(Arrays.asList(allCountries));
Run Code Online (Sandbox Code Playgroud)

ale*_*lex 19

对阵列进行随机播放,然后对前5个元素进行切片.

这将保证5个独特的随机元素.