在Java数组中查找重复项

在Java数组中查找重复项

本文介绍了在Java数组中查找重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无论如何,我有这个非常简单的java程序来找出数组中的2个对象是否相同.当我运行一组唯一对象时,它总是返回1个错误,如果我添加更多相同的对象,它会像往常一样计数.

Anyway, I have this extremely simple java program to find out if 2 objects in an array are the same. How ever when I run it when a set of unique objects it always returns 1 error, If I add more objects that are the same it counts as normal.

这是代码;

int[] array= new int[] {1,245,324,523};

    int size = array.length;
    int error=0;
    System.out.println(error);

    int i = 0;
    for(i=0; i<size; i++){

        if(array[0] == array[i]){
            error= error +1;
        }
        System.out.println(error);
    }

推荐答案

1错误是因为您正在将 array [0] array [0] 进行比较,这当然等于它本身.

The 1 error is because you're comparing array[0] with array[0], which is of course equal to itself.

如果要查找所有成对的重复项,则需要执行两次循环:

If you want to find all pairwise duplicates, you will need to do a double loop:

for(int i=0;i<size;i++){
    for(int j=i+1;j<size;j++){
        if(array[i] == array[j]){
            if(i!=j){
                error = error + 1;
            }
        }
    }
}

您会从此代码中注意到几件事:

You'll notice a few things from this code:

  • j从i + 1开始,而不是0.
  • 仅当i!= j 时,
  • 错误才会增加
  • j starts at i+1, not at 0.
  • error is only incremented when i!=j

第一个是因为您要轮流使用数组中的每个元素来与其他所有元素进行比较.轮到它出现时(在外部循环中),它已经与之前的元素进行了比较,因此不应再次与它们进行比较.

The first is because you're taking turns with each element in your array to compare with every other element. By the time its turn comes around (in the outer loop), it's already been compared to the elements before it, and should not be compared with them again.

第二个是因为您最终将为每个外部循环将一个元素与其自身进行比较.您不想将其计为错误.

The second is because you'll end up comparing an element to itself for each outer loop. You don't want to count it as an error.

这篇关于在Java数组中查找重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 18:25