This post will discuss how to use equal objects as a key in HashMap or HashSet in Java by overriding the 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 check for reference equality.

Let’s consider the following example:

Download  Run Code

Output:

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

 
In the above example, p1 and p2 are considered 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 the 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. The following example uses static utility methods introduced with the 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}]

That’s all about using equal objects as a key in HashMap or HashSet in Java.