why hashCode() does not generate unique hashcode
Because it has no obligation to do so...
Quoting the javadoc of Object.hashCode()
:
It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results.
And indeed, this is a perfectly legal (even though useless) hashCode implementation:
@Override
public int hashCode()
{
return 42;
}
What is required of the .hashCode()
method is that if two objects are equal according to .equals()
, then they should have the same result for .hashCode()
; and the above method fits the bill!
Mind you, in real life, you would never write such a useless hashCode() method as the above...
Note about the default implementations, that is the ones of Object
:
- Its
hashCode()
method calls System.identityHashCode()
;
- Its
equals()
method tests reference equality (that is, for objects o1
and o2
, it tests that o1 == o2
).
If you read the javadoc for Object
carefully, you will see that the contract for both methods is obeyed; The implementation for it is as minimal as you can get, but the contract is obeyed.