Equals and Hashcode Methods in Java

Many Java classes including collection classes (like HashMap, HashTable, HashSet) use hashCode() and equals() methods to compare objects.

If two objects are equal, they should have the same hashCode value,
but two objects having the same hashCode value, doesn’t mean that these two objects are equal (i.e. two different objects might have the same hashCode). See the figure below.

Sun and Cloud objects are not equal but they have the same HashCode value 25.

Java Equals Hashcode Methods

The following code illustrates how equals() and hashCode() methods can be implemented.

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

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

  @Override
  public boolean equals(Object obj) {
    return firstName.equals(((Person)obj).firstName)
        && lastName.equals(((Person)obj).lastName);
  }

  @Override
  public int hashCode() {
    return 31 * firstName.hashCode() + lastName.hashCode();
  }
}

Let’s consider we have following three Person objects (obj1, obj2, ob3). Suppose these objects have the same HashCode value(254398). It’s apparent from the figure, obj1 = obj2 and obj1 ≠ obj3. Now, let’s see how Java Collections API decides whether these objects are equal or not.

Java HashCode Equals Methods

obj1 obj2 Comparison
Step 1:
obj1.hashCode() == obj2.hashCode() => 254398 = 254398
obj1 and obj2 have the same hashCode value, so these two instances might be equal.
Step 2:
obj1.equals(obj2) => true
Equals() method returns true, so these two instances are equal.

obj1 obj3 Comparison
Collections API compares objects in 2 setps. First it calls hashCode() method, then calls equals() method.
Step 1:
obj1.hashCode() == obj3.hashCode() => 254398 = 254398
obj1 and obj3 have the same hashCode value, so these two instances might be equal.
Step 2:
obj1.equals(obj3) => false
Equals() method returns false, so these two instances are not equal.

hashCode() method is used to compare objects effectively. Calling equals() method is expensive (especially if equals() method contains complex logic), it is faster to call hashCode() method. If two objects have different hashCode values, then these objects are different, there is no need to call equals() method.

Related Subjects
Implementing hashCode() (Best Practices)
Java Collections Framework
Override Annotation
Java 1.5 Features