Are immutable objects (other than String
like Integer
and other wrapper classes etc.) good for hashmap keys?
Can anybody explain how?
For the above basic reasoning, key objects are suggested to be immutable. Immutability ensures that we will get the same hashcode every time, for a key object. So it actually solves almost all the problems in one go. But, again, such a class must honor the hashCode() and equals() methods contract.
yes because it is unchangeable. Show activity on this post. If you object is immutable and implements hashcode/equals correctly, you are fine to use them as keys in a hashmap.
If key's hash code changes after the key-value pair (Entry) is stored in HashMap, the map will not be able to retrieve the Entry. Key's hashcode can change if the key object is mutable. Mutable keys in HahsMap can result in data loss.
Interviewer's intent is to judge your knowledge about Hashing Data Structure. The answer is NO. Making keys in any hashing data structure will cause memory leak.
If immutable, the object's hashcode wont change and it allows caching the hashcode of different keys which makes the overall retrieval process very fast. Also for mutable objects ,the hashCode() might be dependent on fields that could change, if this happens you wont be able to find the key (and its value) in the HashMap since hashCode() returns different value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With