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

根据这个答案,粗略地说,如果我们有一个学生对象的 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(代表鞋子类型)的学生人数?


莫回无
浏览 156回答 1
1回答

慕丝7291255

你的equals签名有误。equals方法的正确签名必须如下。public boolean equals(Object other)然后在方法内部你应该检查它是否是可比较的类型,如果你真的需要它是 type Student,你必须检查这个并返回false否则。在您的情况下,这将是您的实施所需的最小更改:public boolean equals(Object other){&nbsp; &nbsp; if (this == other)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; }&nbsp; &nbsp; // This also works if `other` is `null`&nbsp; &nbsp; if (!(other instanceof Student))&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; }&nbsp; &nbsp; // Now we cast it to `Student`&nbsp; &nbsp; final Student student = (Student) other;&nbsp; &nbsp; if (this.getID() != student.getID())&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; }&nbsp; &nbsp; return true;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java