如果比较对象数组索引和对象,如何正确使用equals()?

时间:2018-09-17 16:00:55

标签: java arrays object equals

根据此answer粗略地讲,如果我们有一个Student对象的Classroom对象数组,则class [index]!= student1。我相信这是我在实现equals方法以将array [index]对象与另一个对象进行比较时犯的错误。我相信array [index]和我要比较的对象是相同的。

下面的代码显示了我的getNumStudents方法,在该方法中,我尝试计算学生ID在班级中出现的次数。 ID代表他或她喜欢的品牌鞋(课堂外练习)。这个方法在我的教室对象类中,该类实现了一个接口。

@Override
public int getNumStudents(T anEntry) {
    int count = 0;
    for (int index = 0; index < numberOfEntries; index++) {

       if (roster[index].equals(anEntry)) )
        {
            counter++;
        } 
    } 

    return count;
}

我的equals方法就是这样,并在学生课堂中实现:

public boolean equals(Student student) {
    if (this == student)
    {
        return true;
    }
    if (student == null)
    {
        return false;
    }
    if (this.getID() != student.getID())
    {
        return false;
    }

    return true;
}

我不知道我是否正确地进行了hashCode的覆盖,但在学生类中,它是这样的:

   @Override
    public int hashCode() {
    int result = 17;
    result = 31 * result + studentID;
    return result;
  }

我已经将错误的范围缩小到了最可能的位置:

   if (roster[index].equals(anEntry)) )

具体地

roster[index].equals(anEntry))

我应该调用什么或应该如何调整getNumStudents(T anEntry)方法以正确返回Classroom对象数组中具有特定ID(代表鞋子类型)的学生人数?

1 个答案:

答案 0 :(得分:2)

您的equals签名错误。

equals方法的正确签名必须如下。

public boolean equals(Object other)

然后在方法内部,应检查它是否具有可比较的类型,并且如果确实需要将其归为Student类型,则必须检查该值,否则返回false

在您的情况下,这将是实施所需的最小更改:

public boolean equals(Object other)
{
    if (this == other)
    {
        return true;
    }

    // This also works if `other` is `null`
    if (!(other instanceof Student))
    {
        return false;
    }

    // Now we cast it to `Student`
    final Student student = (Student) other;

    if (this.getID() != student.getID())
    {
        return false;
    }

    return true;
}