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

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

    I think you can't. The reason is, your equals() method is not transitive.

    Transitivity means for three non-null x, y, z, if x.equals(y), y.equals(z), then x.equals(z). In your example, an object x={id: 1, name: "ha"}, y={id: 1, name: "foo"}, z={id: 2, name: "bar"} have this property (x.equals(y) and y.equals(z)). However, x.equals(z) is false. Every equals() method should have this property, see the Java API docs.

    Back to hashing functions: Every function yields an equivalence defined by f(x)==f(y). That means if you are interested in comparison of the function values and want it to return true if x==y (and possibly in other cases), you'll receive a transitive relation, which means you have to consider at least a transitive closure of objects' equivalence. In your case, the transitive closure is the trivial relation (everything equals to anything). Which means you can't distinguish different objects by any function.

提交回复
热议问题