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
- How to create an unordered_map of user defined class in C++?
- How to create an unordered_set of user defined class or struct in C++?
- How to create a user defined javap tool?
- User-defined Custom Exception in Java
- Swap two Strings without using third user defined variable in Java
- Using TreeMap to sort User-defined Objects in Java
- HashMap Class Methods in Java with Examples | Set 1 (put(), get(), isEmpty() and size())
- Java | How to create your own Helper Class?
- How to create Immutable class in Java?
- Does JVM create object of Main class (the class with main())?
- ArrayList vs. HashMap in Java
- HashMap put() Method in Java
- HashMap and TreeMap in Java
- Initialize HashMap in Java
- Hashmap vs WeakHashMap in Java
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.