Howdy!
Raghu wrote:
It is appropriate according to the contract that 2 objects can equal even if their hashcodes are not equal, but is it not a mandatory situation.
The question:
if(x1.hashcode()!=x2.hashcode()) - if the above statement evaluates to true, ie if hascodes for x1 and x2 are not equal, then x2.equals(x1) will always be true.
The statement - as it is - is false.
The contract says:
If two objects are equal they must have the same hash code.
So if the hash codes are different, the two objects can not be equal. Provided they are fulfilling the contract.
Rember the bucket analogy: The hash codes are used for a sort of pre-grouping objects before the equals
test is performed.
If the hash codes are different the equals test will not be performed.
If you have
Then the output is
true
[Raghu@ad3ba4, Raghu@1372a1a]
Equals is overridden to return true in any case, hashCode is not overridden, so it returns the hashCode of class Object which are always different.
Testing the equals method directly returns true due to the override, but when you really use the hashCode for hashing, both objects - despite the fact that they are equal - will be added to a set. Showing that the contract is violated.
I think the easiest way to understand this hashCode and equals contract is always to think of the bucket analogy.
Yours,
Bu.