Are two Java objects with same hashcodes not necessarily equal?
I understand why providing same hashcode for two equal (through equals
) objects is important. But is the vice versa true as well, if two objects have same hashcode do they have to be equal? Does the contract still hold? I cannot find an example where this could happen, because if all those attributes that are taking part in equals method are being used to override hashcode method as well then we will always same hashcode of objects that are equal. Please comment.
Solution 1:
If two objects have the same hashcode
then they are NOT necessarily equal. Otherwise you will have discovered the perfect hash function.
But the opposite is true: if the objects are equal, then they must have the same hashcode
.
Solution 2:
The purpose of the hashCode
function is allow objects to be quickly partitioned into sets of things that are known to unequal to all items outside their own set. Suppose one has 1,000 items and one divides them into ten roughly-equal-sized sets. One call to hashCode
could quickly identify the item as being not equal to 900 of the items, without having to use equals
on any of those items. Even if one had to use equals
to compare the item to 100 other items, that would still be only 1/10 the cost of comparing it to all 1000 items. In practice, even in a large collection, hashCode
will often eliminate 99.9% or more of the unequal items, leaving at most a handful to be examined.