Home  >  Article  >  Java  >  How Does Overriding `hashCode()` and `equals()` Impact HashMap Performance?

How Does Overriding `hashCode()` and `equals()` Impact HashMap Performance?

Susan Sarandon
Susan SarandonOriginal
2024-11-01 17:51:02789browse

How Does Overriding `hashCode()` and `equals()` Impact HashMap Performance?

Understanding how equals and hashCode work in a HashMap

HashMap in Java uses a combination of hashCode() and equals() methods to efficiently store and retrieve key-value pairs. When adding a new key-value pair, the hashCode() method of the key is first calculated to determine the hash bucket in which the entry will be placed. The equals() method is then used to check for duplicate keys within the selected bucket.

In the given test code, the ToDos class defines a primitive implementation of equals(), ensuring that objects with the same day field will be considered equal. When the line // public int hashCode() { return 9; } is uncommented, all ToDos objects, regardless of their day field, are forced to return the same hashCode() value. As a result, all ToDos objects are mapped to the same hash bucket, irrespective of their day field.

When the map.size() method is invoked with the commented-out line, the ToDos objects with different day fields (t1, t2, t3) are placed in different hash buckets due to their distinct hashCode() values. Consequently, map.size() accurately returns the count of three.

Conversely, when the line is uncommented, the ToDos objects are all mapped to the same hash bucket, with the map.size() method subsequently returning a count of two. This is because the HashMap considers all ToDos objects "logically equivalent" as they return the same hashCode() value.

In summary, the use of hashCode() and equals() methods is crucial for HashMap's efficient operation. By overriding only the hashCode() method, it's essential to ensure that logically equivalent keys generate consistent hashCode() values. Overriding only the equals() method can lead to performance issues due to the increased number of comparisons required to determine logical equivalence. Striking the right balance between efficient hashing via hashCode() and ensuring object equality through equals() is key to optimal HashMap usage.

The above is the detailed content of How Does Overriding `hashCode()` and `equals()` Impact HashMap Performance?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn