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.
st1.setId(2);
st1.setName(“Spring”);
As we changes objects content, It’s hashcode is also chnaged, and now whenever you try to get the value for st1,
map.get(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
Thank you!
https://javainterviewquestions.in/
I like this web site so much, bookmarked.
Thanks for your blog, nice to read. Do not stop.