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

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

    I'm pretty sure Zach's right - there's no non-trivial hashcode to do this.

    Pseudo-proof:

    Consider any two non-equal values, X=(id1, name1) and Y=(id2, name2).

    Now consider Z=(id2,name1). This is equal to both X and Y, so must have the same hashcode as both X and Y. Therefore X and Y must have the same hashcode - which means all values must have the same hashcode.

    There's a reason why you've got into a weird situation - you're breaking the transitive nature of equals. The fact that X.equals(Z) and Z.equals(Y) should mean that X.equals(Y) - but it doesn't. Your definition of equality isn't suitable for the normal contract of equals.

提交回复
热议问题