This week's book giveaway is in the Mac OS forum. We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line! See this thread for details.
The question is about the hashCode and equals contract. You have to figure out which of the return statements are legal. For example...
return 0; is legal but not efficient. It returns the same hash every time return a+b; is legal since it is a function of both a and b and the hashcode will be the same even when the numbers are negative. return a-b; is illegal since the hashCode is different for negative numbers.
Originally posted by Sathishkumar Ethiraju: Hey John, Could you be please clear on return a-b; is illegal since the hashCode is different for negative numbers.
Basically, you are trying to follow the rule that, if the equals() methods returns true, the hashcode should be the same.
If you examine the equals() method, if (a=1, b=2) in one object, and (a=2, b=1) in another object, they should be equal -- according to the equals() method. However, if the hash code is "a-b", it will be positive in one case and negative in the other. So... using "a-b" as the formula for hashcode doesn't work.