i have a class whose equality is based on 2 fields such that if either one is equal then the objects of this type are considered equal. how can i write a hashCode() function for
I don't think a nontrivial hashcode exists. Also, your equals()
violates the general contract as stated in the API --- it is not transitive:
(1,2)
equals (1,3)
(4,3)
equals (1,3)
But (4,3)
is not equal to (1,2)
.
For the sake of completeness, I present to you the Skeet-Niko proof =)
Claim: The hashcode must be the trivial constant function.
Proof: Let (a,b)
and (c,d)
be two objects with distinct hashcodes, i.e. h(a,b) ≠ h(c,d)
. Consider the object (a,d)
. By the OP's definition, (a,d)
is equal to (a,b)
, and (a,d)
is equal to (c,d)
. It follows from the hashcode contract that h(a,d) = h(a,b) = h(c,d)
; a contradiction.