Showing posts with label hashmap object as key. Show all posts
Showing posts with label hashmap object as key. Show all posts

Tuesday, 9 May 2023

Why Should an Object Used As the Key should be Immutable

Question) Why Should an Object Used As the Key should be Immutable? 
This is another follow-up to the previous core Java interview questions. It's good to test the depth of technical knowledge of candidate by asking more and more question on the same topic. If you know about Immutability, you can answer this question by yourself. The short answer to this question is key should be immutable so that hashCode() method  always return the same value.

Since hash code returned by hashCode() method depends on upon the content of object i.e. values of member variables. If an object is mutable than those values can change and so is the hash code. If the same object returns different hash code once you inserted the value in HashMap, you will end up searching in different bucket location and will not able to retrieve the object. That's why a key object should be immutable. It's not a rule enforced by the compiler but you should take care of it as an experienced programmer.