How to create a Java HashMap of user defined class type?
Pre-requisite: Internal working of HashMap, HashMap
If we wish to create a HashMap of our own class, we need to ensure that the hashcode() of the key of HashMap doesn’t change as if it happens then it is impossible to get object value of the key from HashMap.
On runtime, JVM processes hash code for each object and give it on interest. When we alter an objects’ state, 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.
One of the ways of doing this is by making key objects IMMUTABLE. Immutability allows you to get same hashcode every time, for a key object. This is the primary motivation behind why Immutable classes like String, Integer or other wrapper classes are a decent key object applicant. Learn more about this here- How to make class Immutable?
Geeks1 Geeks2 Geeks1
Please Login to comment...