...

/

HashMap: How to Design a Good Key

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 ...