How to use equal objects as a key in HashMap or HashSet in Java

In this post, we will see how to use equal objects as a key in HashMap or HashSet in Java by overriding equals() and hashCode() method of the object.


 

Problem:

If a class does not override the equals() and hashCode() methods of the Object class and an object of such class is used as a key for Map or Set in Java, the default implementation of these methods are used which simply checks for reference equality.

Let’s consider below example:

Download   Run Code

Output:

[{John, 20}, {John, 20}, {Carol, 16}]

 
In the above example, p1 and p2 are considered as two separate keys by the HashSet even though they have equal fields. Therefore, two keys will only be equal if they are in-fact the same object.

 

Solution:

If we need key equality on different objects with same value of instance variables, we need to implement equals() and hashCode() on the key.

There are several methods to override equals() and hashCode() methods in Java. Below example uses static utility methods introduced with Objects class in Java 7 that provides for computing the hash code of an object and comparing two objects.

 

Download   Run Code

Output:

[{Carol, 16}, {John, 20}]

 
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)

Loading...

Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂
 


Leave a Reply

avatar
  Subscribe  
Notify of