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

前端 未结 10 2149
执念已碎
执念已碎 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:32

    Ok, in your scenario, ignoring the API requirements for a second, there is no non-constant hash function

    Imagine there were a hashfunction which has different values for

    (a,b), (a,c), b!=c, then hash(a,b) != hash(a,c), eventhough (a,b) = (a,c).

    Similarly, (b,a) and (c,a) must emit the same hashCode.

    Let's call our hash-function h. We find:

    h(x,y) = h(x,w) = h(v,w) forall x,y,v,w.

    Hence, the only hashFunction that does what you want is constant.

提交回复
热议问题