【发布时间】:2018-09-18 00:07:59
【问题描述】:
根据answer,粗略地说,如果我们有一个学生对象的 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 覆盖,但它是(在 Student 类中):
@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(代表鞋子类型)的学生人数?
【问题讨论】:
-
如果 getId 是 int,你为什么不检查 roster[index].getId() == anEntry.getId()。
-
@AshraffAliWahab 我没有发布整个代码,但这是因为我在课堂上使用泛型
-
@AshraffAliWahab 另外,根据我的 IDE, roster[index] 和 anEntry 是两个不同的东西。不一样的类型。