Skip to main content

Command Palette

Search for a command to run...

Why hashCode() should be overridden when overriding equals() in java?

Updated
1 min read
Why hashCode() should be overridden when overriding equals() in java?
B

Experienced Java/JavaScript full-stack developer over 6 years of extensive expertise serving key role on elite technical teams developing enterprise software for healthcare, apple ad-platform, banking, and e-commerce. Adaptable problem-solver with high levels of skill in Groovy, Java, Spring, Spring Boot, Hibernate, JavaScript, TypeScript, Angular, Node, Express, React, MongoDB, IBM DB2, Oracle, PL/SQL, Docker, Kubernetes, CI/CD pipelines, AWS, Micro-service and Agile/Scrum. Strong technical skills paired with business-savvy UI design expertise. Personable team player with experience collaborating with diverse cross-functional teams.

The hashCode() method is used to generate a unique numerical value (hash code) for each object, which is used to quickly identify the object in a collection. The equals() method is used to determine if two objects are equal.

The general contract of hashCode() method is that it should return the same value for two objects that are equal according to the equals() method. Therefore, if you override the equals() method, it is important to also override the hashCode() method to ensure that two equal objects have the same hash code.

If hashCode() and equals() methods are not overridden correctly, it can cause issues when trying to access objects from collections like HashMap, HashSet or Hashtable.

For example, if two objects are considered equal, but have different hashcodes, these two objects will be stored in different locations in the collection, which will lead to unexpected results when trying to retrieve them.

In short, when two objects are equal, their hashcodes must be equal too, hence it's important to override hashCode() whenever equals() is overridden in order to maintain consistency and avoid unexpected results.

More from this blog

Bikash Mainali

75 posts

Experienced Java/JavaScript full-stack developer with 8 years of extensive expertise serving key role on elite technical teams developing and designing software.