根据这个答案,粗略地说,如果我们有一个学生对象的 Classroom 对象数组,则 class[index] != student1。我相信这是我在实现我的 equals 方法以将 array[index] 对象与另一个对象进行比较时所犯的错误。我相信 array[index] 和我比较的对象是相同的。下面的代码显示了我的 getNumStudents 方法,在该方法中我尝试计算学生 ID 在课堂中出现的次数。ID代表他或她喜欢的品牌鞋(课外练习)。这个方法在我的课堂对象类中,它实现了一个接口。@Overridepublic 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 回答
慕丝7291255
TA贡献1859条经验 获得超6个赞
你的equals签名有误。
equals方法的正确签名必须如下。
public boolean equals(Object other)
然后在方法内部你应该检查它是否是可比较的类型,如果你真的需要它是 type 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;
}
添加回答
举报
0/150
提交
取消