Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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
Miscellaneous
Interview Questions
Programming Questions
What is the default value of Boolean field?
Is null instance of anything?
Iterate list in reverse order
Can I use calloc and malloc as variable name in Java?
Check whether a number is 32 bit integer or not


This post first appeared on Java Tutorial : Blog To Learn Java Programming, please read the originial post: here

Share the post

How to get Original Hash code of the object?

×

Subscribe to Java Tutorial : Blog To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×