Originally posted by Damien Howard:
The hashcode function can basically be anything you want, but a good hashcode function should make use of the same vars as the equals
Actually, this is incorrect. Look at the rules again that I listed. The equals method is saying that two objects are equal if:
- a and b of first equals a and b of second
or
- a of first equals b of second and b of first equals a of second
(1) is a correct answer because it passes the most important rule. Two equal objects will return the same hashcode. (Unequal objects will return the same hashcode but that is irrelevant.)
(2) is incorrect. Let's take an example. We have two objects:
first --> a=1, b=2
second --> a=2, b=1
These objects are equal by the equals method so they must return the same hashcode. If they return a, they won't return the same hashcode.
3) this is correct. Using the example from above, they would both return 3.
4) this is incorrect. using the example above,
first would return -1 and second would return +1.
5) this is correct because ^ returns the same value, independent of order.
first --> 0001^0010 = hashcode of 0000
second --> 0010^0001 = hashcode of 0000
6) gibberish
So the correct answers are 1,3,5