Thursday, 24 May 2018

How to get the system hash code of an object?

Every object in java has a hashCode value associated with it. Ideally, the hashcode of an object is generated by converting the internal address of the object into an integer. But the implementation of hashCode depends on the vendor.

Employee.java
package com.sample.model;

public class Employee {

 private int id;
 private String name;

 public Employee() {

 }

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

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

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

Test.java
package com.sample.test;

import com.sample.model.Employee;

public class Test {

 public static void main(String args[]) throws ClassNotFoundException {
  Employee emp = new Employee();

  emp.setId(1);
  emp.setName("PTR");

  System.out.println("Object Hash Code : " + emp.hashCode());

 }
}

Output

Object Hash Code : 1956725890

You can always override the hashCode method and provide custom implementation. In that case, how can you get the System generated hashcode of the object?


java.lang.System class provides 'identityHashCode' method to get the system generated hashCode of the object.

Employee.java
package com.sample.model;

public class Employee {

 private int id;
 private String name;

 public Employee() {

 }

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

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

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

 @Override
 public String toString() {
  return "Employee [id=" + id + ", name=" + name + "]";
 }

 @Override
 public int hashCode() {
  final int prime = 31;
  int result = 1;
  result = prime * result + id;
  result = prime * result + ((name == null) ? 0 : name.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 (id != other.id)
   return false;
  if (name == null) {
   if (other.name != null)
    return false;
  } else if (!name.equals(other.name))
   return false;
  return true;
 }

}

Test.java
package com.sample.test;

import com.sample.model.Employee;

public class Test {

 public static void main(String args[]) throws ClassNotFoundException {
  Employee emp = new Employee();
  
  emp.setId(1);
  emp.setName("PTR");
  
  System.out.println("Object Hash Code : " + emp.hashCode());
  System.out.println("System Hash Code : " + System.identityHashCode(emp));

 }
}

Output

Object Hash Code : 80558
System Hash Code : 1956725890


No comments:

Post a Comment