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

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

    After re-read the question.

    You may auto-complete the another field when one of them being updated.

    --

    EDIT: My code may say better then my English.

    void setName(String value){
      this.id=Lookup.IDbyName(value);
    }
    void setID(String value){
      this.name=Lookup.NamebyId(value);
    }
    

    EDIT 2:

    The code on the question may wrong as will always return true unless you've set both the id & name.

    If you really want a method that do partial equals, create you own API that named "partialEquals()".

提交回复
热议问题