检查数组java、android studio中的重复值
我想检查finalChallenges ArrayList中的重复项。实际上,我用while-cicle来填充最后的挑战列表。如果finalChallenges arrayList包含重复项,请将其删除并继续检查数组java、android studio中的重复值,java,android,arraylist,Java,Android,Arraylist,我想检查finalChallenges ArrayList中的重复项。实际上,我用while-cicle来填充最后的挑战列表。如果finalChallenges arrayList包含重复项,请将其删除并继续 Random random = new Random(); while (finalChallenges.size()<21) { int index = random.nextInt(listChallenges.size()); finalChal
Random random = new Random();
while (finalChallenges.size()<21) {
int index = random.nextInt(listChallenges.size());
finalChallenges.add(listChallenges.get(index));
if(compare(finalChallenges)){
inalChallenges.remove(index);
}
}
比较方法:
public boolean compare(ArrayList<Challenges> compArray) {
for (int j=0;j<compArray.size();j++) {
for (int k = j + 1; k < compArray.size(); k++) {
if (k != j && compArray.get(k) == compArray.get(j))
return true;
}
}
return false;
}
更好的解决方案:
List<Integer> indices = new ArrayList<>(listChallenges.size());
List<Challenges> finalChallenges = new ArrayList<>();
for (int i = 0; i < listChallenges.size(); indices.add(i++));
for (int i = 0; i < Math.min(21, listChallenges.size()); ++i) {
int index = indices.remove(random.nextInt(indices.size());
finalChallenges.add(listChallenges.get(index));
}
如果你想得到随机值,为什么不只是Collectionsshuffle呢?您只需迭代一次,然后就可以确保至少不会得到两个相同的随机元素。除此之外,您可能还想查看另一个集合。如果您不想要副本,为什么要使用列表而不是集合?@Rogue listChallenges Arraylist有更多的元素,如finalchallenges,我只能放置21个。因此我认为Collectionsshuffle在这里不起作用。@Francesc抱歉,但我不理解这个问题。我应该在哪里使用这台电视机?请贴一张。由于您在这里没有询问任何特定于Android的问题,因此我建议您创建一个简单的小ol'Java程序来说明您正在尝试做什么。它应该足够完整,我们可以自己编译和运行它,并看到与您得到的完全相同的输出。谢谢,现在我理解了,但在此之后,应用程序被冻结。此代码很脆弱,如果列表中的条目少于21个,它将永远不会退出循环。此外,如果条目数接近21,则可能需要很长时间才能退出循环。您最好使用另一种方法。是的,此代码非常脆弱。另一方面,我解决了这个问题。谢谢你的帮助。
List<Integer> indices = new ArrayList<>(listChallenges.size());
List<Challenges> finalChallenges = new ArrayList<>();
for (int i = 0; i < listChallenges.size(); indices.add(i++));
for (int i = 0; i < Math.min(21, listChallenges.size()); ++i) {
int index = indices.remove(random.nextInt(indices.size());
finalChallenges.add(listChallenges.get(index));
}
Random random = new Random();
ArrayList<Challenges> temp = new ArrayList<Challenges>(listChallenges.size());
for (Challenges item : listChallenges) temp.add(item);
while (finalChallenges.size()<21 && temp.size()>0) {
int index = random.nextInt(temp.size());
finalChallenges.add(temp.get(index));
temp.remove(index);
}