Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Immutable objects and hashmap keys [closed]

Tags:

java

Are immutable objects (other than String like Integer and other wrapper classes etc.) good for hashmap keys?

Can anybody explain how?

like image 714
a Learner Avatar asked Nov 26 '13 09:11

a Learner


People also ask

What is suggested to have immutable objects in keys in HashMap?

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.

Are HashMap keys immutable?

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.

What will happen if class is mutable and used as key in 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.

Is HashMap mutable?

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.


1 Answers

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.

like image 156
Renjith Avatar answered Oct 18 '22 04:10

Renjith