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

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

    EDIT: I didn't read the question carefully.

    --

    I'll use commons-lang jar.

    XOR the members hashCode should works. As they should implements hashCode() and equals() correctly.

    However, your code may wrong if you don't protect your hashCode. Once it was hashed, it should not be changed. It should be prevented from being happen.

    public hashCode(){
       return new AssertionError();
    }
    

    or

     public class MyClass {
       final int id;
       final String name;
       // constructor
     }
    

    or

    public class MyClass {
       private int id;
       private String name;
       boolean hashed=false;
       public void setId(int value){
         if(hashed)throw new IllegalStateException();
         this.id=value;
       }
       public void setName(String value){
         if(hashed)throw new IllegalStateException();
         this.name=value;
       }
       // your equals() here
       public hashCode(){
         hashed=true;
         return new HashCodeBuilder().append(id).append(name).toHashCode();
       }
    }
    

提交回复
热议问题