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.
hashCode in HotSpot is a random number. If you overwrite it, then it s no longer a random value. See this post for example.hashCode may be related to a memory address, but it doesn't have to be. Javadoc is not wrong, it just can be a bit misleading.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());
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.
intand your object contains aStringyou cannot possibly have a different hashcode for each object. Therefore for two objects to be equal it is a neccessary but not sufficient condition for the hashcodes to be equal. Put into other words, a hashcode has no type 1 error but in order to achieve that it has a potentially high rate of type 2 error.