Equals() and hashCode() in Java


Object class define equals, hashCode methods which closely belong together.


Class has a notion of logical equality. Characteristics of equality are as follows.

  • Reflexive (x = x)

  • Symmetric (x = y => y = x)

  • Transitive (x = y and y = z => x = z)

  • Consistent

  • For non null x, x.equals(null) should return false

equals() method in object class is used for comparing equality between two objects.

For example. you define Money class

class Money {
int amount;
String currencyCode;
Money income = new Money(55, "USD");
Money expenses = new Money(55, "USD");
// false
boolean balanced = income.equals(expenses)

The default implementation of equals() just compare memory address between two objects.

you want tow Money object is equals if they have same amount & currencyCode, you can override equals method like below.

public boolean equals(Object o) {
    if (o == this)
        return true;
    if (!(o instanceof Money))
        return false;
    Money other = (Money)o;
    boolean currencyCodeEquals = (this.currencyCode == null && other.currencyCode == null)
      || (this.currencyCode != null && this.currencyCode.equals(other.currencyCode));
    return this.amount == other.amount && currencyCodeEquals;


hashCode() should returns an integer value representing the current instance of the class. it should be calculated with the definition of equality for the class. it is used for behavior in hash related classes like HashMap, HashTable. so if equals() is ovveriden, you also have to override hashCode() .