This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
Key Rule here is that if any two objects are meaningfully equivalent (return a true while using the .equals() method) then their two hashcodes should be the same. So (x.equals(y)) is true then (x.hashCode()==y.hashCode()) is true.
(x==y) indicates the two objects are pointing to the same location hence the objects have the same value and as per the rule above the same hashcodes!!
I think with this you can figure out the results are a) and c). Also true true true is also possible.
Java API documentation for class Object, the hashCode() contract says:
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.
b) if equals() and hashcode() methods are implemented appropriately,
if (x.equals(y))evaluates to true then(x.hashCode==y.hashCode())should also returns true
"If two objects are equal according to the equals(Object) method, then calling the hashCode() method on each of the two objects must produce the same integer result."
for d) & e) if (x==y) returns true then both references are pointing to same object (aliases) so equals method should also returns true and consequently the next expression(x.hashCode==y.hashCode() should also returns to true
i hope it will help
Joined: Dec 20, 2005
Very Thanks for your answers.
As per your explanation we can simply say d) and e) are wrong. Because if a==b is true, which means both are same object. So rest all should be true.
I agree with c), a==b can be false but still these objects can have same meaningful data. Example new Integer(1).equals(new Integer(1)) will be true, even though both are different objects.
Now the issue is with a) and b) What i think is, If a) is correct, then b) should be correct. If a) is wrong, then b) should be wrong. If you say a) is correct, that means if a.equals(y) can be false, but still a.hashCode == b.hashCode can be true. Why the other way is wrong ? This is what i am not able to get. Keep in mind a and b are different objects because as per a) and b) a==b is false.