根据这个答案,大致来说,如果我们有一个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(表示鞋子类型)的学生人数?
您的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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句