When you want to use the Object of a custom class as a key in Hashmap, there are several things you need to consider, and that are
- Override hashCode() and equals() in custom class.
- The object of a custom class must be immutable.
map.put(st1 , “One”);
Now, as it is mutable we can easily change it’s value.
As we changes objects content, It’s hashcode is also chnaged, and now whenever you try to get the value for st1,
As per the working of hashmap, it will calculate hashcode and on the basis of it’s hashcode it’s index value will be determined, So now index value is something different like 11, so if 11 is empty we will get result as empty or wrong value instead of One, so that is the reason we must always use the immutable object as key.
Note : If you have any question you can add it in comment