hashCode() method when equals() is based on multiple independent fields

前端 未结 10 2153
执念已碎
执念已碎 2021-02-08 09:16

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

10条回答
  •  别跟我提以往
    2021-02-08 09:25

    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.

提交回复
热议问题