HashMap: How to Design a Good Key

Let's see how we can design a good HashMap key.

The first and foremost requirement for a good key is that it should follow the hashcode() and equals() contract. The contract says:

  1. If two objects are equal, then they must have the same hash code.
  2. If two objects have the same hash code, they may or may not be equal.

This means that the class that is being used as a key must override both equals() and hashcode() methods.

Why overriding both hashcode() and equals() is important

If a class does not override both the hashcode() and equals() method, then it will break the contract and the HashMap may not work. Let’s look at an example. We have an Employee class that has two fields as shown below:

public class Employee {
	int empId;
    String empName;
}

This class overrides the hashcode() method but does not override the equals() method. Ideally, two objects are considered equal if their empId is equal.

Now we will create two Employee objects with the same empId and empName. We will also create a HashMap where the key will be the Employee object, and the value will be the salary. The HashMap should not allow both the Employee objects to be inserted as they are equal.

Get hands-on with 1200+ tech skills courses.