Search code examples
javaequals

Why do equals() implementations always start from self checking even when it's redundant?


I am learning to override Java's equals() method, and I can understand the correctness of many tutorials such as the following from https://www.baeldung.com/java-hashcode#handling-hash-collisions.

public class User {

    private long id;
    private String name;
    private String email;

    // standard getters/setters/constructors
        
    @Override
    public int hashCode() {
        return 1;
    }
        
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null) return false;
        if (this.getClass() != o.getClass()) return false;
        User user = (User) o;
        return id == user.id 
          && (name.equals(user.name) 
          && email.equals(user.email));
    }
    
    // getters and setters here
}

My Question is that the implementation starts from self-checking, like

if (this == o) return true;

but this line seems to be redundant. If o references to the same object, the last checking

User user = (User) o;
return id == user.id 
  && (name.equals(user.name) 
  && email.equals(user.email));

will be true as well.

I have googled a lot, but cannot find any topic related to it.

Why does every implementation of equals() start with self-checking even when there is no need to do that? Is this a performance issue or something?


Solution

  • The first to call to == is an optimization. If this and o are the exact same object (i.e. this == o returns true), there's no need to perform the subsequent following operations of going over all the object's properties and comparing them one by one.