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 Purpose of Spring Configuration File ?

What is Information Hiding in Java ?

How Do You Debug Code in JSP ?

What is the Use of Run Time Polymorphism in Java ?

What is the Difference Between Queue and Stack Data Structures in ...