我有一系列国家.我想从我的数组列表中选择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)