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

Why We Cannot Create a Generic Array in Java ?

What is a WeakHashMap in Java ?

Why Do You Use Upcasting or Downcasting in Java ?

What are the Main Benefits of Collections Framework in Java ?

What is the Different Type of Tag Library Groups in JSTL ?