https://stackoverflow.com/questions/2265503/why-do-i-need-to-override-the-equals-and-hashcode-methods-in-java
https://stackoverflow.com/questions/27581/what-issues-should-be-considered-when-overriding-equals-and-hashcode-in-java?rq=1
Override only equals
If only equals is overriden, then when you call myMap.put(first,someValue) first will hash to some bucket and when you call myMap.put(second,someOtherValue) it will hash to some other bucket (as they have a different hashCode). So, although they are equal, as they don’t hash to the same bucket, the map can’t realize it and both of them stay in the map.
Although it is not necessary to override equals() if we override hashCode(), let’s see what would happen in this particular case where we know that two objects of MyClass are equal if their importantField is equal but we do not override equals().
Override only hashCode
Imagine you have this
MyClass first = new MyClass(“a”,“first”);
MyClass second = new MyClass(“a”,“second”);
If you only override hashCode then when you call myMap.put(first,someValue) it takes first, calculates its hashCode and stores it in a given bucket. Then when you call myMap.put(second,someOtherValue) it should replace first with second as per the Map Documentation because they are equal (according to the business requirement).
But the problem is that equals was not redefined, so when the map hashes second and iterates through the bucket looking if there is an object k such that second.equals(k) is true it won’t find any as second.equals(first) will be false.
Hashing retrieval is a two-step process:
Find the right bucket (using hashCode())
Search the bucket for the right element (using equals() )
Java中equals与hashCode的重要性
本文探讨了在Java中正确实现equals和hashCode方法的必要性。仅覆盖equals可能导致Map存储重复项,而仅覆盖hashCode则可能导致Map无法识别相等的对象。深入理解两者的关系对于避免编程陷阱至关重要。
2万+





