I found this sentence in my book:
If hashcodes of two objects are equals, that may not mean that objects are equals.
Can someone please explain me this sentence?
I found this sentence in my book:
If hashcodes of two objects are equals, that may not mean that objects are equals.
Can someone please explain me this sentence?
Consider, for example, two objects of the Long class. Since hashCode
returns an int
, and the long
(and Long
) type has a larger range than int
, this means there must be two Long
objects that have the same hashCode
even though they are not equal to each other.
Answer is simple: hashCode()
accidentally can produce the same number for two totally different objects.
A hash code is a numeric value that is used to insert and identify an object in a hash-based collection.
It is a fixed size value so it can't be unique for every existing object so from time to time it suffers collisions. Basically, hashCode() can produce the same value for two different objects.
Example:
String first = "wh";
String second = "xI";
System.out.println(first.equals(second));
System.out.println(first.hashCode() + " " + second.hashCode());
In hash base implementation when ever you check for equality of two objects it check first hash code first, if it's same for both objects, then it calls equals method it that also return true then only two objects are considered equal.
2 equal object will have the same hashcode.
2 objects with the same hascode don't have to be equal.
Lets say the hascode method produces it's value by counten the letters of a name (bad practice, but I'm using this example to explain it), but the equals compares each character:
Paul and Mary would both return the hascode 4, but the characters are not equal
Even if the hashCode of an object would be the memory address at creation time it still must be stored inside the object header because of the garbage collector.
The garbage collector may freely move objects around to do its work, so the current memory address may change anytime. However:
the {@code hashCode} method must consistently return the same integer, provided no information used in {@code equals} comparisons on the object is modified.