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

What is the Use of a Dictionary Class in Java ?

What is Observer Design Pattern in Java ?

What is the Difference Between a Cookie and a Session Object in J ...

How Will You Handle InterruptedException in Java ?

What is the Main Benefit of IOC Principle in Java ?