71

是否有关于如何在考虑超级字段的子类equals()中覆盖&的特定规则?知道有很多参数:超级字段是私有/公共的,有/没有getter ...hashCode()

例如,Netbeans 生成的 equals() 和 hashCode() 不会考虑超级字段......和

    new HomoSapiens("M", "80", "1.80", "Cammeron", "VeryHot").equals(
    new HomoSapiens("F", "50", "1.50", "Cammeron", "VeryHot"))

将返回 true :(

public class Hominidae {

    public String  gender;
    public String  weight;
    public String  height;

    public Hominidae(String gender, String weight, String height) {
        this.gender = gender;
        this.weight = weight;
        this.height = height;
    }
    ... 
}

public class HomoSapiens extends Hominidae {
    public String name;
    public String faceBookNickname;

    public HomoSapiens(String gender, String weight, String height, 
                       String name, String facebookId) {
        super(gender, weight, height);
        this.name = name;
        this.faceBookNickname = facebookId;
    }
    ...  
}

如果您想查看 Netbeans 生成的 equals() 和 hashCode() :

public class Hominidae {

    ...

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

    @Override
    public int hashCode() {
        int hash = 5;
        hash = 37 * hash + (this.gender != null ? this.gender.hashCode() : 0);
        hash = 37 * hash + (this.weight != null ? this.weight.hashCode() : 0);
        hash = 37 * hash + (this.height != null ? this.height.hashCode() : 0);
        return hash;
    }

}


public class HomoSapiens extends Hominidae {

    ...

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

    @Override
    public int hashCode() {
        int hash = 7;
        hash = 89 * hash + (this.name != null ? this.name.hashCode() : 0);
        hash = 89 * hash + (this.faceBookNickname != null ? this.faceBookNickname.hashCode() : 0);
        return hash;
    }
}
4

10 回答 10

69

孩子不应该检查父母的私人成员

显然,所有重要的字段都应该考虑到相等和散列。

幸运的是,您可以轻松满足这两个规则。

假设您没有卡住使用 NetBeans 生成的 equals 和 hashcode,您可以修改 Hominidae 的 equals 方法以使用 instanceof 比较而不是类相等,然后直接使用它。像这样的东西:


    @Override  
    public boolean equals(Object obj) {  
        if (obj == null) { return false; }  
        if (getClass() != obj.getClass()) { return false; }  
        if (! super.equals(obj)) return false;
        else {
           // compare subclass fields
        }

当然,hashcode 很简单:


    @Override     
    public int hashCode() {     
        int hash = super.hashCode();
        hash = 89 * hash + (this.name != null ? this.name.hashCode() : 0);     
        hash = 89 * hash + (this.faceBookNickname != null ? this.faceBookNickname.hashCode() : 0);     
        return hash;     
    }     

不过,说真的:NetBeans 没有通过调用超类方法来考虑超类字段是怎么回事?

于 2010-01-14T20:41:54.910 回答
23

我更喜欢使用commons-lang 包中的EqualsBuilder(和 HashcodeBuilder)来使我的 equals() 和 hashcode() 方法更易于阅读。

例子:

public boolean equals(Object obj) {
 if (obj == null) { return false; }
 if (obj == this) { return true; }
 if (obj.getClass() != getClass()) {
   return false;
 }
 MyClass rhs = (MyClass) obj;
 return new EqualsBuilder()
             .appendSuper(super.equals(obj))
             .append(field1, rhs.field1)
             .append(field2, rhs.field2)
             .append(field3, rhs.field3)
             .isEquals();
}
于 2010-01-14T19:42:57.900 回答
8

一般来说,跨子类实现 equals 很难保持对称和传递。

考虑一个检查字段xand的超类,以及检查, andy的子类。xyz

因此,子类 == 超类 == 子类,其中子类的第一个实例和第二个实例之间的 z 不同,这违反了合同的传递部分。

这就是为什么 equals 的典型实现会检查getClass() != obj.getClass()而不是执行 instanceof。在上面的示例中,如果 SubClass 或 Superclass 进行 instanceof 检查,则会破坏对称性。

所以结果是子类当然可以考虑 super.equals() 但也应该进行自己的 getClass() 检查以避免上述问题,然后另外检查自己的字段是否相等。这将是一个奇怪的类的鸭子,它根据超类的特定字段改变自己的 equals 行为,而不仅仅是超类返回 equals。

于 2010-01-14T20:02:07.130 回答
6

规则是:

  • 它是自反的:对于任何非空引用值 x,x.equals(x) 应该返回 true。
  • 它是对称的:对于任何非空引用值 x 和 y,当且仅当 y.equals(x) 返回 true 时,x.equals(y) 才应该返回 true。
  • 它是可传递的:对于任何非空引用值 x、y 和 z,如果 x.equals(y) 返回 true 并且 y.equals(z) 返回 true,则 x.equals(z) 应该返回 true。
  • 它是一致的:对于任何非空引用值 x 和 y,x.equals(y) 的多次调用始终返回 true 或始终返回 false,前提是没有修改对象上 equals 比较中使用的信息。
  • 对于任何非空引用值 x,x.equals(null) 应该返回 false。
  • 每当重写该方法时,一般都需要重写 hashCode 方法,以维护 hashCode 方法的一般约定,即相等的对象必须具有相等的哈希码

来自Object.equals()

因此,请使用满足规则所需的字段。

于 2010-01-14T19:33:06.737 回答
3

好吧,HomoSapiens#hashcodeCPerkins 的回答就足够了。

@Override     
public int hashCode() {     
    int hash = super.hashCode();
    hash = 89 * hash + Objects.hash(name);     
    hash = 89 * hash + Objects.hash(faceBookNickname);     
    return hash;     
}

如果您希望这些父字段( gender, weight, height) 起作用,一种方法是创建父类型的实际实例并使用它。感谢上帝,它不是一个抽象类。

@Override
public boolean equals(Object obj) {
    if (obj == null) {
        return false;
    }
    if (getClass() != obj.getClass()) {
        return false;
    }
    final HomoSapiens other = (HomoSapiens) obj;
    if (!super.equals(new Hominidae(
        other.gender, other.weight, other.height))) {
         return false;
    }
    if (!Objects.equals(name, other.name)) return false;
    if (!Objects.equals(faceBookNickname, other.faceBookNickname))
        return false;
    return true;
}

我正在添加一种方法来(我认为)解决这个问题。关键是添加一个松散地检查相等性的方法。

public class Parent {

    public Parent(final String name) {
        super(); this.name = name;
    }

    @Override
    public int hashCode() {
        return hash = 53 * 7 + Objects.hashCode(name);
    }

    @Override
    public boolean equals(final Object obj) {
        return equalsAs(obj) && getClass() == obj.getClass();
    }

    protected boolean equalsAs(final Object obj) {
        if (this == obj) return true;
        if (obj == null) return false;
        if (!getClass().isAssignableFrom(obj.getClass())) return false;
        final Parent other = (Parent) obj;
        if (!Objects.equals(name, other.name)) return false;
        return true;
    }

    private final String name;
}

来了Child

public class Child extends Parent {

    public Child(final String name, final int age) {
        super(name); this.age = age;
    }

    @Override
    public int hashCode() {
        return hash = 31 * super.hashCode() + age;
    }

    @Override
    public boolean equals(final Object obj) {
        return super.equals(obj);
    }

    @Override
    protected boolean equalsAs(final Object obj) {
        if (!super.equalsAs(obj)) return false;
        if (!getClass().isAssignableFrom(obj.getClass())) return false;
        final Child other = (Child) obj;
        if (age != other.age) return false;
        return true;
    }

    private final int age;
}

测试...

@Test(invocationCount = 128)
public void assertReflective() {
    final String name = current().nextBoolean() ? "null" : null;
    final int age = current().nextInt();
    final Child x = new Child(name, age);
    assertTrue(x.equals(x));
    assertEquals(x.hashCode(), x.hashCode());
}

@Test(invocationCount = 128)
public void assertSymmetric() {
    final String name = current().nextBoolean() ? "null" : null;
    final int age = current().nextInt();
    final Child x = new Child(name, age);
    final Child y = new Child(name, age);
    assertTrue(x.equals(y));
    assertEquals(x.hashCode(), y.hashCode());
    assertTrue(y.equals(x));
    assertEquals(y.hashCode(), x.hashCode());
}

@Test(invocationCount = 128)
public void assertTransitive() {
    final String name = current().nextBoolean() ? "null" : null;
    final int age = current().nextInt();
    final Child x = new Child(name, age);
    final Child y = new Child(name, age);
    final Child z = new Child(name, age);
    assertTrue(x.equals(y));
    assertEquals(x.hashCode(), y.hashCode());
    assertTrue(y.equals(z));
    assertEquals(y.hashCode(), z.hashCode());
    assertTrue(x.equals(z));
    assertEquals(x.hashCode(), z.hashCode());
}
于 2016-08-20T15:25:13.370 回答
2

因为继承破坏了封装,实现equals() 和hashCode() 的子类必须,必然,说明它们的超类的特殊性。我已经成功地从子类的方法对父类的 equals() 和 hashCode() 方法进行了编码调用。

于 2010-01-14T19:48:09.780 回答
2

关于接受的@CPerkins 答案,我认为给定的 equals() 代码不会可靠地工作,因为 super.equals() 方法也可能会检查类是否相等。子类和超类不会有相同的类。

于 2013-05-10T16:46:56.803 回答
1

听起来您的父(超级)类没有覆盖等于。如果是这种情况,那么当您在子类中覆盖此方法时,您需要比较父类中的字段。我同意使用公共 EqualsBuiler 是要走的路,但您确实需要小心不要破坏 equals 合同的对称/交易部分。

如果您的子类向父类添加属性并且父类不是抽象的并且覆盖等于您将遇到麻烦。在这种情况下,您应该真正关注对象组合而不是继承。

我强烈推荐 Joshua Block 的 Effective Java 部分。它很全面,而且解释得很好。

于 2010-01-14T22:57:38.490 回答
1

值得注意的是,IDE自动生成可能已经考虑到超类,只要超类的equals()和hashCode()存在。也就是应该先自动生成super的这两个函数,再自动生成child。我在 Intellj Idea 下得到了正确的例子:

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

    TActivityWrapper that = (TActivityWrapper) o;

    return data != null ? data.equals(that.data) : that.data == null;
}

@Override
public int hashCode() {
    int result = super.hashCode();
    result = 31 * result + (data != null ? data.hashCode() : 0);
    return result;
}

当您不首先自动生成超级时,问题就会发生。请在上面的 Netbeans 下查看。

于 2016-09-08T06:32:23.717 回答
0

我相信他们现在有一种方法可以为您做到这一点:

EqualsBuilder.reflectionEquals(this, o);

HashCodeBuilder.reflectionHashCode(this);

于 2018-06-06T12:34:11.417 回答