Friday, March 25, 2022

Why overriding equals() and hashcode() is required in Java?

First go through the code below

Map<String, Integer> stringMap = new HashMap<>();
stringMap.put("a", 1);
stringMap.put("b", 2);
stringMap.put("a", 3);
System.out.println(stringMap);

The output for the above code will be 

{a=3, b=2}

As you can since the key is same even though we inserted 3 key/value pairs the map contains only two key/value pairs since the key a is repeating.

Now check the below code

Map<Employee, Integer> employeeMap = new HashMap<>();
employeeMap.put(new Employee("anu"), 1);
employeeMap.put(new Employee("binoy"), 2);
employeeMap.put(new Employee("anu"), 3);
System.out.println(employeeMap);
class Employee {
private String name;

public Employee(String name) {
this.name = name;
}

@Override
public String toString() {
return "Employee{" + name + '}';
}
}

The output for the above code will be

{Employee{binoy}=2, Employee{anu}=3, Employee{anu}=1}

Even though the name of the employee is the same the map is treating it as a separate key, because default implementation only compares the object reference to decide whether an object is equal or not. Note that these references are values generated by hashcode() method. 

You can override the equals() and hashcode() method to solve the above problem. Below is the sample on how to override these methods.

class Employee {
private String name;

public Employee(String name) {
this.name = name;
}

@Override
public String toString() {
return "Employee{" + name + '}';
}

@Override
public boolean equals(Object o) {
// If object is compared with itself
if (o == this) return true;

if (!(o instanceof Employee)) return false;

// typecast o to Employee to compare data members
Employee e = (Employee) o;
// Compare the data members and return accordingly
return name.compareTo(e.name) == 0;
}

@Override
public int hashCode() {
return this.name.hashCode();
}
}
public class Main {
public static void main(String[] args) {
Map<Employee, Integer> employeeMap = new HashMap<>();
employeeMap.put(new Employee("anu"), 1);
employeeMap.put(new Employee("binoy"), 2);
employeeMap.put(new Employee("anu"), 3);
System.out.println(employeeMap);
}
}

The output  now will be

{Employee{binoy}=2, Employee{anu}=3}









No comments:

Post a Comment