繁体   English   中英

覆盖超类中的 equals 方法

[英]overriding the equals method from the superclass

当我们从超类重写 equals() 方法时,需要 hashcode() 方法的新实现。 equals() 和 hashcode() 之间的约定被保留。

Contract between equals and hashcode method need to be kept when your are going to use that class in hashing based collections, like hashmap, hashset etc which uses hashcode method to calculate the hash index and equals method to check the equality. 否则你可以忽略哈希码。 请参阅下面的 URL 以获取有关 hashmap 中的 equals 和哈希码方法覆盖的更多信息。 https://www.thetechnojournals.com/2019/10/why-hashmap-key-should-be-immutable-in.html

equalshashCode方法将(就像任何其他方法一样)从超类继承。

如果这些仍然适用于子类,您可以保持原样。

JDK中有这样的例子:

  • Stack扩展Vector扩展AbstractList
  • Stack只是从Vector继承equals
  • Vector覆盖AbstractList中的equals ,但仅添加synchronized然后调用super.equals
  • ArrayList也扩展了AbstractList ,但它使用遵循相同逻辑的实现覆盖了equals ,但可以更有效,因为它知道至少有一个参与者是ArrayList

但请记住,

  • 您现在将使用同一段代码比较所有组合中的 Super <-> Super、Super <-> Sub、Sub <-> Sub 实例
  • this实际上可以是一个子类时,像this.getClass()这样的东西可能会返回意想不到的东西

如果这导致您的比较逻辑出现问题,则由您决定。

暂无
暂无

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

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