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!