Wednesday, September 27, 2017

HashCode and Equals Contract

hashCode() and equals() in Java has a certain contract which must be followed in order to have the correct behavior.

In below example, Employee as an object is being used as key . So if Employee e1 and e2 are said to be equal if there Ids are equal then we've to override hashCode() as well because two objects are equal only if there hashCode is equal.

package com.hashCodeContract;
import java.util.HashMap;
public class Employee {
     String name;
     int compId;

     public Employee(String name, int compId) {
          super();
          this.name = name;
          this.compId = compId;
     }

     public Employee() {

     }

     public String getName() {
          return name;
     }

     public void setName(String name) {
          this.name = name;
     }

     public int getCompId() {
          return compId;
     }

     public void setCompId(int compId) {
          this.compId = compId;
     }

     public static void main(String[] args) {

          Employee e1 = new Employee("Paras", 10);
          Employee e2 = new Employee("Paras", 10);

          HashMap<Employee, Integer> map = new HashMap<>();
          map.put(e1, 1);
          map.put(e2, 1);

          System.out.println("Get " + map.get(e2));
          System.out.println("Equals " + e1.equals(e2));
          System.out.println("HashCode " + e1.hashCode());
          System.out.println("HashCode " + e2.hashCode());

          System.out.println("Map size " + map.size());

          System.out.println(map.get(new Employee("Paras", 10)));
     }

     public int hashCode() {
          return 123;
     }

     public boolean equals(Object emp) {
          return (this.name.equals(((Employee) emp).getName()));
     }
}

Output
Get 1
Equals()   true
hashCode() 123
hashCode() 123
Map size   1

1

No comments:

Post a Comment