What is the Difference Between equals and hashCode in Java?

🆚 Go to Comparative Table 🆚

The main difference between equals and hashCode in Java lies in their purpose and functionality.

equals:

  • Compares the content of two objects for equality.
  • Might not always return true for the same object, due to changes in object state.
  • Default behavior is inherited from the Object class and needs to be overridden for custom comparison.

hashCode:

  • Provides a unique integer hash code value representing the object.
  • Its purpose is to offer a fast and efficient way to compare objects.
  • Should be updated whenever the object state changes that affects hash code calculation.

There are certain rules that must be followed when implementing equals and hashCode in Java. Some of these rules include:

  1. If two objects are equal according to equals() method, their hashCode() must be the same.
  2. If two objects are unequal according to equals() method, their hashCode() are not required to be different.
  3. Each invocation of hashCode() on the same object that hasn't been changed must produce the same result each time.

In summary, equals is used to compare the content of two objects, while hashCode is used to generate a unique hash code value for an object. These methods are crucial when working with hash-based collections, such as HashMap, to ensure efficient storage and retrieval of objects based on their unique identities.

Comparative Table: equals vs hashCode in Java

The equals() and hashCode() methods in Java serve different purposes and have distinct properties. Here is a table highlighting the differences between them:

Method Purpose Requirements Contract
equals() Comparison of object content
Checks if two objects are the same
Symmetric (x.equals(y) == y.equals(x))
Reflexive (x.equals(x) == true)
Transitive (x.equals(y) && y.equals(z) implies x.equals(z))
If you override equals(), you must also override hashCode() to avoid violating the contract
hashCode() Generates a unique hash value for an object
Used in hashing-based collections (e.g., HashMap, HashSet)
Not required to be symmetric, reflexive, or transitive If two objects are unequal according to equals() method, their hash codes are not required to be different

In summary, the equals() method compares the content of two objects and checks if they are the same, while the hashCode() method generates a unique hash value for an object, which is used in hashing-based collections. The equals() and hashCode() methods have different contracts and purposes, and it is essential to implement them correctly to avoid violating their contracts.