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

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

    Have you intentionally defined equality as when ids are equal OR names are equal.. Shouldnt the "OR" be a "AND" ?

    If you meant "AND" then your hashcode should be calculated using the very same or less (but never use fields not used by equals) fields you are by equals().

    If you meant "OR" then you r hashgcode should not include id or name in its hashcode calculation which doesnt really make sense.

提交回复
热议问题