从数组中随机选择元素,但要保证唯一性

9

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

3
您不希望它们独特吗?如果是这样,为什么需要比较它们,您已经拥有的应该可以很好地工作。 - Mark Peters
你的标题和问题是相互矛盾的。你想要独特的还是不想要? - Perception
你是不是?请澄清这个矛盾的标题。 - adarshr
抱歉,我的表达不太好...我会修改问题。 - Badr Hari
@alex:也许把那个转换成一个答案? - Mark Peters
1个回答

19

将数组随机排序并取前5个元素。

这将保证获取到5个唯一的随机元素。


1
很棒的想法...我也将代码添加到我的问题中。谢谢 :) - Badr Hari

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接