简体   繁体   English

为什么我应该重写equals和hashcode方法来跟随scnerio

[英]why should I override equals and hashcode method for following scnerio

为什么我需要重写以直接访问Hash映射中的值。也就是说,如果按照HashMap将数据插入到hashmap中,则可以通过将Key设置为Integer来获取值,而将Object用作Value。在这种情况下,必须重写equals()和hashCode()方法?请提出建议。

No, you don't need to override anything to use an object as a value in a HashMap . 不,您不需要重写任何内容即可将对象用作HashMap

Only keys need to have a working hashCode() . 密钥需要具有有效的hashCode()

However, you need to implement these two methods (technically only equals , but these two are a set, really) if you want to use things like Map#containsValue , List#indexOf or Collection#contains (and these should not just be using reference identity). 但是,如果要使用Map#containsValueList#indexOfCollection#contains类的东西,则需要实现这两种方法(从技术上讲,这仅是equals ,但实际上这两个是一个集合)(并且这些方法不应仅使用引用)身份)。

hashCode() is used to search for a specific elem when you want to retrieve it from a hashTable. 当您想从hashTable中检索特定的elem时,可以使用hashCode()来搜索它。 hashCode() doesn't have to be distinct. hashCode()不必区分。 in fact, you could just return the same integer for all your instance, but then, elems are stored in a list instead of a hashTable, and will cause a performance problem. 实际上,您可以为所有实例返回相同的整数,但是,elems存储在列表中而不是hashTable中,这将导致性能问题。

  • By default implementation of hashCode() (which is the implementation of Object for subClass to extents from )of JVM returns a integer according to the memory address of the object, so this should be enough, but this implement was not required by the JVM standard. 缺省情况下,JVM的hashCode() (这是子类的Object的实现,范围从扩展)根据对象的内存地址返回一个整数,因此这足够了,但是JVM标准不需要此实现。 。

  • By default(Class object ), implementation of equals() will return true and only return true when they have same reference , ie obj1 == obj2 . 默认情况下(Class object ),equals()的实现将返回true并且仅当它们具有相同的引用时才返回true ,即obj1 == obj2 read this 读这个

keep in mind that: 请记住:

  • equal objects must have same hashCode() 相等的对象必须具有相同的hashCode()
  • those have same hashCode() are not required to be equal to each other. 那些具有相同hashCode()不需要彼此相等。

I think override of hashCode() is not needed in most situations(not extends from other Class), cause modern JVMs has done pretty good job for you. 我认为在大多数情况下(不需要从其他Class继承),不需要重写hashCode() ,因为现代JVM对您来说做得很好。

So conclusion is: 因此结论是:

if your super class have overwrite the hashCode() and equals() method, then you should override them, or at least take a look at the implementation, and decide whether you should override them. 如果您的超类已覆盖hashCode()equals()方法,则应覆盖它们,或者至少应看一下实现,并决定是否应覆盖它们。

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

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