Java with HashMap, Immutable Classes and Wrapper Classes
In Java Immutable classes is one of the important feature as a developer we might already know. Also In Java HashMap is one of the common and most usable collection everyone have used at least once.
There is very common question frequently asked in interview is "How HashMap works internally" and almost everyone have better explanation on it with terms like hashing techniques, hashcode and equals methods, linked lists and buckets, indexing etc.
In this article I would like to explain about uncommon things about Immutable classes, Wrapper classes and HashMap and how they work together accurately using hashcode and equals methods.
Why Immutable classes should use as a keys is HashMap?
HashMap is work with key-value pairs and when we put() data in HashMap it generates the HashMap based on state of the key. state means the data which available inside that particular key. using that data HashMap generate hashcode and use that hashcode as a index value.
In next operation when we want to read that particular HashMap data get() method again generate hashcode with given parameter. in this case also state of that key object is use to generate hashcode and find data using that hashcode as a index value.
So twist here is state of that particular key should not be change at the time of put() and get() operation then only HashMap will generate same hashcode for get() and put() operation. so this means your HashMap key should be Immutable and no one should change state of that key.
It is recommended that HashMap use "String" key type when possible. So the reason behind this recommendation is String is Immutable class. defined as a final and fields also final, no setters only getters and public constructors.
Why Wrapper classes also we use as a keys in HashMap?
Wrapper classes are Immutable by default so like String they are also given same benefit when we use them as a Key in HashMap.
Wrapper classes are immutable because they represent the primitive's and primitive's should not change there state anyway.
State changing object problems and solutions?
If you don't want to be make your object Immutable as well as you need to change state always but don't want to change hashcode value every time when state changes.
If this is the scenario then,
On runtime, JVM processes hash code for each object and give it on interest. When we change the state of any object, JVM calculates its hash code again which may result in memory leak. To make things work what we have to do is make sure that state change for a key object does not change the hash code of object. i.e. the key must have properly overridden equals() and hashcode() methods for it to work correctly.
Always use IDE or Objects utility class for generate hashcode, which is recomended performance point of views.