Originally posted by nik arora:
Hi chandra,
Can you explain me how those 4 answers what you mentioned satisfies
equals() contract?
Ok!
a. return 0;
b. return a;
c. return a+b;
d. return a*a;
e. return a/2;
Let us take options one by one:
a-
Your equals method says, two objects are equal when their a value matches.
Now if equals(...) method returns true for two objects their hashCode() must
be equal. If your hashCode() returns 0, it is ok although it is not efficient because it returns 0 for all regardless they are equal or not.
b- It is correct because hashCode() will the value of a. It is also fine.
Two objects with the same a value are equal.
c- a+b is incorrect because, you are not using b in your equals method.
It will return wrong hashCode for two objects with same a value.
Suppose
for object1 a=5, b=10;
for object2 a=5, b=12;
your equals() method will return true because it is comparing on behalf of value of "a", but hashCode() of these two objects will be different (15 for
object1 and 17 for object2) that is against the equals() hashCode() contract.
d- and e- can easily be understood if you get the above description well.
a*a and a/2 will return same for two objects with the same "a" value.
In the option e you are dividing by constant so it will always be same for a value "a" if "a" does not change.