0

I just read from a book and it said that as long as we override an equals() method from the Object class, its hashCode() method should be overriden also, but I do not really understand why we have to override the hashCode() method also. Let's consider a following example below:

public class Employee {
    public int employeeId;
    public String firstName, lastName;
    public int yearStarted;

    Employee(){}

    Employee(int employeeID){
        this.employeeId = employeeID;
    }

//  @Override
//  public int hashCode() {
//      return employeeId;
//  }

    public boolean equals(Object e) {
         if(!(e instanceof Employee)){
             return false;
         }
         else {
             Employee newEmp = (Employee)e;
             return this.employeeId == newEmp.employeeId;
         }

    }

    public static void main(String[] args) {
        Employee one = new Employee(101);
        if (one.equals(new Employee(101)))
            System.out.println("Success");
        else
            System.out.println("Failure");
    }
}

And when running I get "Success" result, while I override only an equals(), but not hashCode(). So what does the process flow that related to the hashCode() when overriding the equals() method actually look like and in which case do we need to override both hashCode() and equals()? Thank you!

Ock
  • 1,262
  • 3
  • 18
  • 38

1 Answers1

0

It is rather a convention to override both equals() and hashCode(). The reason for that is that many library utilities, such as HashMap rely on the consistency of both methods. In fact, for two objects a and b, if a.equals(b) is true, then also a.hashCode() == b.hashCode() should be true.

You might want to read about hash-based data structures to understand this requirement in more detail, e.g., here: https://en.wikipedia.org/wiki/Hash_table

Sebastian Kruse
  • 318
  • 2
  • 7