如何重写equals方法

How to rewrite the equals method

看到有同事这样写的:

 @Override
 public boolean equals(Object obj) {
    if (this == obj) {
        return true;
    }
    if (obj == null) {
        return false;
    }
    if (getClass() != obj.getClass()) {
        return false;
    }
    final ImageCode other = (ImageCode) obj;
    if ((this.code == null) ? (other.code != null) : !this.code.equals(other.code)) {
        return false;
    }
    return true;
}

然后,我建议改成这样:

@Override
public boolean equals(Object obj) {
    if (this == obj) {
         return true;
    }
    if (!(obj instanceof Parent)){
         return false;
    }
    final ImageCode other = (ImageCode) obj;
    if ((this.code == null) ? (other.code != null) : !this.code.equals(other.code)) {
         return false;
    }
    return true;
 }

但是他告诉我这是错误的,instanceof不能用于equals方法。我不明白他为什么这么说。

您可以在 equals 中使用 instanceof。 Java 一直在使用它。参见例如String

public boolean equals(Object anObject) {
    if (this == anObject) {
        return true;
    }
    if (anObject instanceof String) {
        String anotherString = (String)anObject;

        // More code ...
        return true;
    }
    return false;
}

@dejvuth, 如果 anObject 是 String 的实例,那么为什么我们需要进行类型转换。你可以直接使用它。我认为不检查 instanceOf 就可以继续。 只是您可能需要对对象进行类型转换。你可以在这里查看我的代码。

http://www.javavni.com/is-hashcode---and-equals---required-together.html