posted 13 years ago
If two objects are equal according to the equals method, then they must have the same hashcode value in order to satisfy the equals-hashcode contract. Consider this situation:
You have a ValuePair object with a=2 and b=7, and you have another ValuePair object with a=7 and b=2. According to the equals method, these two objects are equal. Therefore, according to the contract, these two objects must return the same value from their hashCode() methods.
But if we choose return a; for the body of the hashCode() method, then one object will have a hashcode of 2, and the other will have a hashcode of 7, so we've broken the contract by writing an incorrect set of hashCode() and equals() implementations. If we chose return 0; then the two objects would have the same hashcode value, so that implementation would be correct.
SCJA 1.0 (98%), SCJP 1.4 (98%)