给出以下代码:
public static int countSames(Object[] a) {
int count = 0;
for (int i = 0; i < a.length; i++) {
for (int k = 0; k < a.length; k++) {
if (a[i].equals(a[k]) && i != k) {
count += 1;
break; //Preventing from counting duplicate times, is there way to replace this?
}
}
}
return count;
}
我想知道是否有一个不使用 break 语句的解决方案,因为我听说过它的不好做法。 但如果没有中断,此方法将返回 6,而不是数组 {'x', 'x', 'x'} 所需的 3。
最佳答案
如果您想查找数组中唯一元素的数量,请尝试使用这种方法,因为它只有一个循环,因此效率很高。
private static int findNUmberOfUnique(String[] array) {
Set<String> set=new HashSet<>();
for(int i=0;i<array.length;i++){
if(!set.contains(array[i])){
set.add(array[i]);
}
}
return set.size();
}
如果我没有清楚地理解您的要求,请告诉我。
关于java - 查找数组中相同的元素并防止重复计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60206544/