gpt4 book ai didi

java - EQ_SELF_USE_OBJECT 错误

转载 作者:行者123 更新时间:2023-11-30 07:46:04 25 4
gpt4 key购买 nike

我正在编写一个 equals 方法,其中如果两个名字具有相同的名字、中间名和姓氏,则它们被视为相等。但是,我不断收到错误

"This class defines a covariant version of the equals() method, but inherits the normal equals(Object) method defined in the base java.lang.Object class. The class should probably define a boolean equals(Object) method."

当我将其更改为 Object other 作为参数时,我收到“没有此类方法”错误。

public boolean equals(Name other) {

boolean sameFirstName = firstName.equals(other.firstName);
boolean sameMiddleName = middleName.equals(other.middleName);
boolean sameLastName = lastName.equals(other.lastName);
if (sameFirstName && sameMiddleName && sameLastName) {
return true;
}
return false;
}

最佳答案

您必须使用对象类型作为名为“其他”的参数。然后进行检查和类型转换实例。请引用这个answer

如果您使用 Java 7 或更高版本,则可以使用以下代码:

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return Objects.equals(firstName, person.firstName) &&
Objects.equals(middleName, person.middleName) &&
Objects.equals(lastName, person.lastName);
}

并且IDE中有一个自动生成的equals:

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;

Person person = (Person) o;

return !(firstName != null ? !firstName.equals(person.firstName) : person.firstName != null)
&& !(middleName != null ? !middleName.equals(person.middleName) : person.middleName != null)
&& !(lastName != null ? !lastName.equals(person.lastName) : person.lastName != null);

}

请注意,还应该进行 NPE 检查。

关于java - EQ_SELF_USE_OBJECT 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33948126/

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