java - 搜索数组中的重复项

标签 java arrays comparison

如果我用这些数据初始化一个 person 对象数组

myPeople[0] = new Person("Alice", "Foo", 22 );
myPeople[1] = new Person("Alice", "Foo", 22 );
myPeople[2] = new Person("Bob", "Bar", 2);
myPeople[3] = new Person("Joe", "Blogs", 64);
myPeople[4] = new Person("Jane", "Joe", 42);

我希望我的方法返回重复项的数量。在这种情况下,它将是 2,因为人物 0 和人物 1 是彼此重复的。如果我要将对象 2 更改为相同的对象,它应该返回 3。目前,我的方法返回 1(有两个重复项)和 4(有三个重复项)。

有问题的方法:

public static int searchForClones(Person[] array){
    int numberOfClones=0;
    for(int j =0; j<array.length-1; j++)
    {
        String tmp1 = array[j].getFirstName();          //Store first element of the array in tmp so it can be compared
        String tmp3 = array[j].getLastName();   
        for(int i = 0; i<array.length-1; i++)           //Loop to compare for every element in the array
        {   
            String tmp2 = array[i].getFirstName();      //Do the same for the next element
            String tmp4 = array[i].getLastName();
            if(i!=j)                                    //If i an j aren't the same element
            {

                if(tmp1.equals(tmp2) && tmp3.equals(tmp4)   //and if they match
                    && array[i].getAge()==array[i+1].getAge())
                {   
                    numberOfClones++;                   //increment the number of clones
                }
           }
       }
    }
    return numberOfClones;
}

我真的很感激任何帮助,因为我认为唯一的问题是我增加克隆数量的方式。也许我需要检查一些内容并在之后增加适当的数字?

最佳答案

这是一种方法:

public static int searchForClones(Person[] array){
    if(array == null || array.length == 0) return 0;

    return array.length - new HashSet(Arrays.asList(array)).size();
}

一如既往,确保正确实现 Person 对象的 equalshashCode 方法。

关于java - 搜索数组中的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15059880/

相关文章:

java - 如何解决 .java 文件中的 java.lang.RuntimeException : Stub! 错误?

java - Spring声明式事务管理不起作用

javascript - 将大量数字组合成一个数字的问题

python - 如何在 scipy 中创建一个巨大的稀疏矩阵

C++:ptr_container 比较

linux - 如何简化 bash 中的比较?

opencv - 定性比较两个图像Opencv

java - Weblogic 异常 : javax. naming.NameNotFoundException : Unable to resolve 'jdbc.payment' . Resolved 'jdbc' ;剩余名称 'payment'

java - 实现具有泛型和接口(interface)的组合

java - 计算数组中最大递增数字序列