Well, keep in mind that the equals method only checks to see if a given ValuePair object contains the same two values. It doesn't matter if they're stored in the same order. So, this code should result in two ValuePair objects that are logically equal:
The contract of the HashCode method is as follows:
Now, let's look at the solutions and see which one's conform to all these rules and which don't.
- Solution A will always be a valid hash code method. It's the most inefficient one you can create, but it meets all 3 criteria.
- Solution B isn't a valid hashcode method in this case. While those two objects are equal, invoking hashCode on "one" would result in a 5 while invoking hashCode on "two" would result in a 6. That violates rule 2.
- Solution C works just fine because addition is commutative. That means that you can change the order of the operands without impacting the result. 5 + 6 = 11. 6 + 5 = 11. Therefore, invoking that hashCode method on either object will return the same value - this hashCode is valid.
- Solution D doesn't work because, unlike addition, subtraction is not commutative. 5 - 6 = -1. 6 - 5 = 1. The hashCode methods would return different results for logically equivalent objects. That's a no-no.
- Solution E works because the XOR operation (^ - which is also Shift-6) is commutative, just as addition is.
- Solution F fails because, like subtraction, the operation is not commutative. Try it for yourself and see.
I hope that helps.
Edit: By the way, I wrote an article about Hash Codes
here, in case you're interested.
[ March 25, 2005: Message edited by: Corey McGlone ]