Java Object hashCode Method Example



In this example, we will demonstrate the usage of java.lang.Object.hashCode() method with an example.

Object hashCode() Method

The java.lang.Object.hashCode() method returns a hash code value for the object. This method is supported for the benefit of hash tables such as those provided by java.util.HashMap.
Read the general contract of hashCode at Object hashCode() API Doc.

Object hashCode() Method Example

The following example shows the usage of lang.Object.hashCode() method:
public class Person {
  private String firstName;
  private String 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;
  }

  public static void main(String[] args) {
     Person person = new Person();
     person.setFirstName("Ramesh");
     person.setLastName("Fadatare");

     System.out.println(person.hashCode());

     Person person1 = new Person();
     person1.setFirstName("Ramesh");
     person1.setLastName("Fadatare");
     System.out.println(person1.hashCode());
 }
}
Let us compile and run the above program, this will produce the following result −
-1066062211
-1066062211
By definition, if two objects are equal, their hashcode must also be equal. If you override the equals() method, you change the way two objects are equated and Object's implementation of hashCode() is no longer valid. Therefore, if you override the equals() method, you must also override the hashCode() method as well.

Comments