gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 02:02:29 24 4
gpt4 key购买 nike

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

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

@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;
}

关于java - 如果比较对象数组索引和对象,如何正确使用 equals()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52371741/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com