This post will discuss how to use an object as a key in hash-based collections like HashMap, HashSet, and Hashtable in Java.

Problem:

First, let’s take an example to demonstrate the default behavior on using an object as a key in hash-based collections like HashMap, HashSet, and Hashtable in Java.

Download  Run Code

Output:
[{name='John', age=20}, {name='John', age=20}]

 
As evident from the generated output, the HashSet contains both e1 and e2 objects even though e1 and e2 have the same value of instance variables. This is because two objects are considered equal only if their references point to the same object, which is not the case here.

Solution:

The hash-based collections are organized like a sequence of buckets, where the hash code value of an object is used to determine the bucket where the object would be stored, and the object is linearly searched in the bucket using the equals method. Therefore, to use an object as a key in HashMap, HashSet, or Hashtable in Java, we need to override equals and hashcode methods of that object since default implementation of these methods simply check for the instance equality.

 
Let’s take an example to demonstrate the benefit of overriding the equals and hashCode method in Java:

Download  Run Code

Output:
[{name='John', age=20}]

 
As evident from the generated output, the set contains only one Employee object even though two different Employee objects are added. This is because we have overridden both equals() and hashCode() method in the Employee class, and e1 and e2 objects now points to the same bucket and also holds the same location within the bucket.

That’s all about using an object as a key in HashMap or HashSet in Java.

 
Also See:

Why do we need to override equals and hashcode methods in Java?