Why an Object Used as Key in HashMap Should Be Immutable in Java ?

The Key object should be immutable so that hashCode() method always return the same value for that object.

The Hashcode returned by hashCode() method depends on values of member variables of an object. If an object is mutable, then the member variables can change. Once the member variables change, the Hashcode changes. If the same object returns different hash code at different times, then it is not reliable to be used in the HashMap.

When you insert the object, the Hashcode is X, the HashMap will store it in bucket X. But when you search for it the Hashcode is Y, then HashMap will look for the object in bucket Y. So you are not getting what you stored.

To solve this, a key object should be immutable.

Although, the compiler does not enforce this rule, a good programmer always remembers this rule.



You May Interest

How Strategy Design Pattern is Different From State Design Patter ...

Why ListIterator Has add Method But Iterator Does Not Have in Jav ...

How Can We Prevent a Deadlock in Java ?

What is a Singleton Class in Java ?

How Will You Handle InterruptedException in Java ?