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

How to properly use equals() if comparing an object array index and an object?

根据这个,粗略地说,如果我们有一个学生对象的 Classroom 对象数组,class[index] != student1。我相信这是我在实现我的 equals 方法来比较 array[index] 对象和另一个对象时犯的错误。我相信数组 [index] 和我正在比较的对象是相同的。

下面的代码显示了我的 getNumStudents 方法,我在该方法中尝试计算学生 ID 在 class 中出现的次数。 ID代表他或她喜欢的品牌鞋(讲课练习题)。此方法在我的 classroom 对象 class 中,它实现了一个接口。

@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 方法就是这样,并在学生中实现 class:

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,但这里是(在 Student class 中):

   @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) 方法以正确 return Classroom 对象数组中具有特定 ID(代表鞋子类型)的学生数量?

您的 equals 签名有误。

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

public boolean equals(Object other)

然后在方法内部你应该检查它是否是可比较的类型,如果你真的需要它是类型 Student,你必须检查这个和 return 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;
}