Why we need to override equals() when overriding hashCode() ?
Sebastian Janisch wrote:Comes down to the algorithm of collections.
HashCode determines where objects are located (two identical hashcodes do not necessarily mean 2 equal objects), and equals determines equality between those objects.
Thanks for your reply.
as you said, "two identical hashcodes do not necessarily mean 2 equal objects". then could we say, two different hashcodes definitely mean two not-equal object ?
Do you mean, hashcode in Object is ONLY for algorithm of collection ? then too much waste, because we NOT always use collections.
Henry Wong wrote:
If hashcode is only use for collection, then we need to implement hashcode when we need collection.
As a writer of the data class, sometimes you can't control whether your class will be used in a collection. Some people do put instances of Object in a hashing collection.
Yes, even if you do not design your classes for collection or do not plan for it, someone might do it, and if object had no hashCode and equals, evil things would happen.
He also indicates that when you fail to override hashCode you are breaking the following Object contract: equal objects must have equal hash codes. A consequence of this the inability of Map<K,V>.get(Object key) to work properly because, under certain conditions, the get method will not check for object equality for objects that have different hashCodes.
For a thorough treatment I highly recommend reading Item 9 "Always override hashCode when you override equals" of Effective Java.