Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

How to override and implement the hashCode and equals method in Java ?.

Program to demonstrate how to override and implement the hashCode and equals method in Java.

import java.util.Date;

// 1. Create Employee class
public class Employee {

 // 2. Define three properties of Employee
 // as age, name and dateOfBirth.
 private int age;
 private String name;
 private Date dateOfBirth;

 // 3. Create a Employee constructor setting three properties.
 public Employee(int age, String name, Date dateOfBirth){
  this.age = age;
  this.name = name;
  this.dateOfBirth = dateOfBirth;
 }

 // 4. Overriding equals method into the Employee class.
 @Override
 public boolean equals(Object object) {

  boolean isEquals = false;

  if(this == object){ 
   isEquals = true;
  }

  if(null == object || this.getClass() != object.getClass()){ 
   isEquals = false;
  }

  Employee employee = (Employee) object;

  if((this.age == employee.age) &&  
    (null != this.name && this.name.equals(employee.name)) &&
    (null != this.dateOfBirth && this.dateOfBirth.equals(employee.dateOfBirth))){

   isEquals = true;

  }
  return isEquals;

 }

 // 5. Overriding hashCode() mehtod in the Employee class.
 @Override
 public int hashCode() {
  int hashCode = 10;
  hashCode = (31 * hashCode) + age;
  hashCode = (31 * hashCode) + (name != null ? name.hashCode() : 0);
  hashCode = (31 * hashCode) + (dateOfBirth != null ? dateOfBirth.hashCode() : 0);
  return hashCode;
 }

 public static void main(String[] args) {

  Employee employee1 = new Employee(30, "Dinesh", new Date(1987, 12, 1));
  Employee employee2 = new Employee(31, "Jimmy", new Date(1989, 11, 2));
  Employee employee3 = new Employee(30, "Dinesh", new Date(1987, 12, 1));

  System.out.println("employee1.hashCode() = " + employee1.hashCode());
  System.out.println("employee2.hashCode() = " + employee2.hashCode());
  System.out.println("employee1.equals(employee2) = " + employee1.equals(employee2));

  System.out.println("employee1.hashCode() = " + employee1.hashCode());
  System.out.println("employee3.hashCode() = " + employee3.hashCode());
  System.out.println("employee1.equals(employee3) = " + employee1.equals(employee3));

  System.out.println("employee2.hashCode() = " + employee2.hashCode());
  System.out.println("employee3.hashCode() = " + employee3.hashCode());
  System.out.println("employee2.equals(employee3) = " + employee2.equals(employee3));

 }

}



Output of the program : 

 



Video tutorial to demonstrate how to override hashcode method in Java.








Video tutorial to demonstrate how to override equals method in Java.








 
© 2021 Learn Java by Examples Template by Hubberspot