Tuesday, 11 February 2020

How to get Original Hash code of the object?

Suppose you are given an Employee class, which overrides hashCode method. Now the question is ‘How will you get the original hash code of the object?

Answer
Use the method 'identityHashCode' of System class to get the original hash code.

Example
System.identityHashCode(emp1)

Employee.java
package com.sample.app.model;

public class Employee {
 private String firstName;
 private String lastName;

 public Employee(String firstName, String lastName) {
  super();
  this.firstName = firstName;
  this.lastName = lastName;
 }

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 @Override
 public int hashCode() {
  final int prime = 31;
  int result = 1;
  result = prime * result + ((firstName == null) ? 0 : firstName.hashCode());
  result = prime * result + ((lastName == null) ? 0 : lastName.hashCode());
  return result;
 }

 @Override
 public boolean equals(Object obj) {
  if (this == obj)
   return true;
  if (obj == null)
   return false;
  if (getClass() != obj.getClass())
   return false;
  Employee other = (Employee) obj;
  if (firstName == null) {
   if (other.firstName != null)
    return false;
  } else if (!firstName.equals(other.firstName))
   return false;
  if (lastName == null) {
   if (other.lastName != null)
    return false;
  } else if (!lastName.equals(other.lastName))
   return false;
  return true;
 }

}

App.java
package com.sample.app;

import com.sample.app.model.Employee;

public class App {

 public static void main(String args[]) {
  Employee emp1 = new Employee("Ram", "Gurram");
  
  System.out.println("Hash Code of employee emp1 : " + emp1.hashCode());
  System.out.println("Hash Code of employee emp1 : " + System.identityHashCode(emp1));
  
 }

}

Output
Hash Code of employee emp1 : 2146770941
Hash Code of employee emp1 : 2018699554


You may like

No comments:

Post a Comment