简体   繁体   English

在子类中调用super.equals和super.hashCode?

[英]Calling super.equals and super.hashCode in child class?

If I implement equals() and hashCode() in both the parent and child classes, is it necessary to call super.equals() in equals() in the child class, eg 如果我在父类和子类中都实现equals()hashCode() ,是否有必要在子类中的equals()中调用super.equals() ,例如

public boolean equals(Object obj) {

  if (obj.getClass() != ChildClass.class) {
    return false;
  }

  return super.equals() && this.var == ((ChildClass) obj).var;

}

I am assuming that the parent class is not Object and is giving the correct definition of equals and hashCode. 我假设父类不是Object,并且给出了equals和hashCode的正确定义。

No, that's not necessary, and would probably be wrong. 不,这不是必要的,也可能是错的。 Indeed, part of the reason why you're overriding equal is because super.equals doesn't give the correct behaviour (right?). 事实上,你为什么要覆盖的部分原因equal是因为super.equals没有给出正确的行为(是吗?)。

Or put another way, if super.equals gives the correct behaviour, you probably don't need to go to the trouble of overriding it. 换句话说,如果super.equals给出正确的行为,你可能不需要去覆盖它的麻烦。

But if you are overriding equals , then yes, you need to override hashCode , too. 但是如果你要覆盖equals ,那么是的,你也需要覆盖hashCode

If your super class doesn't implement equals, then calling super.equals will get you the Object implementation which only compares references, so in any normal equals implementation where you want to compare a business key it would actually cause a lot of false negatives. 如果你的超类没有实现equals,那么调用super.equals将获得只实现比较引用的Object实现,因此在任何正常的equals实现中你想要比较一个业务键,它实际上会导致很多漏报。

That said, your implementation above really isn't any different semantically than the default equals implementation in Object since you are just using == for comparison. 也就是说,上面的实现在语义上与Object中的默认equals实现没有任何不同,因为您只是使用==进行比较。

As for hashCode, if you override equals you really should override hashCode in order to keep the contract of the two. 至于hashCode,如果你重写equals,你真的应该覆盖hashCode以保持两者的契约。 For instance, if you are using a business key for equals you should probably use the same business key for the hashcode so that two objects that are equal generate the same hashcode. 例如,如果您使用等于的业务键,则应该对哈希码使用相同的业务键,以便两个相等的对象生成相同的哈希码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM