Hashcode and equals

后端 未结 7 2422
死守一世寂寞
死守一世寂寞 2020-11-30 14:00

equals and hashCode method must be consistent, which means that when two objects are equal according to equals method their hash

7条回答
  •  北海茫月
    2020-11-30 14:33

    In the following code:

    public boolean equals(Object oo) {
        if(oo instanceof Hashvalue) 
            HashValue hh = (HashValue) oo;
    
        if (this.x == hh.x)
            return true;
        else
            return false;
    }
    

    there are a couple of issue: 1. Hashvalue is not recognised by your compiler. It should be "HashValue" 2. hh is out of scope once out of if-block. Hence, compiler error.

    You can change your program to following and it will work:

     public boolean equals(Object oo) {
         if(!(oo instanceof Hashvalue)) 
             return false;
    
         HashValue hh = (HashValue) oo;
         if (this.x == hh.x)
            return true;
         else
            return false;
    }
    

    or you can make it more concise as follows:

     public boolean equals(Object oo) {
         if(oo instanceof Hashvalue && this.x == ((HashValue) oo).x) 
             return true;
         return false;
    }
    

提交回复
热议问题