HashMap: How to Design a Good Key
Let's see how we can design a good HashMap key.
We'll cover the following...
The first and foremost requirement for a good key is that it should follow the hashcode()
and equals()
contract. The contract says:
- If two objects are equal, then they must have the same hash code.
- 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 ...