Search code examples
javaalgorithmequals

why override java's equals() method this way?


I try to override equals() method from Object class.

 @Override
public boolean equals(Object o){
    if(this == o)
        return true; 
    if(!(o instanceof Menu))
       return false;
   Menu menu = (Menu)o; 
   return price == menu.price &&
          Objects.equals(name,menu.name); 
}

From what I learned, if (this==o) is true , then true will be returned as a result of equals method. and the equals method will be stopped.

when people override equals method, they always put if(this == o) with returned value. but if the first if-statement is true , then other if-statement will not executed and other if-statement will not be checked

I don't know why people override equals() method in this way.. I would be really appreciated if someone helps me I could not find the answer to this question.. Thank you so much !


Solution

  • Objects must compare equal to themselves. If you don't add this first check, it's surprisingly easy for an object to not compare equal to itself. Typically, this can happen if you have a float or double field.

    For example, if X is a class with a double field f, then this code is WRONG, because it violates the reflexive rule of equality:

    @Override
    public boolean equals(Object o){
        if(!(o instanceof X))
           return false;
       X x = (X)o;
       return f == x.f;
    }
    

    If you compare an object with f=Double.NaN to itself, it will return false -- because NaN does not compare equal to itself.