How HashMap works

http://javarevisited.blogspot.ro/2011/02/how-hashmap-works-in-java.html

http://stackoverflow.com/questions/6493605/how-does-a-hashmap-work-in-java

They will be stored in the same bucket if their hash codes are the same, and in this case, the hashmap will use equals() to tell them apart.

To use a custom Class as key in a HashMap you have to override
– hashCode() [it is called on: map.put(Key, Value)]
– equals() [it is used on get, if we have the same hashCode for 2 keys]

———–
http://howtodoinjava.com/2013/05/02/how-to-design-a-good-key-for-hashmap/

Key’s hash code is used primarily in conjunction to its equals() method, for putting a key in map and then getting it back from map. So, our only focus point is these two methods. So if hash code of key object changes after we have put a key value pair in map, then its almost impossible to fetch the value object back from map. It is a case of memory leak.

On runtime, JVM computes hash code for each object and provide it on demand. When we modify an object’s state, JVM set a flag that object is modified and hash code must be AGAIN computed. So, next time you call object’s hashCode() method, JVM recalculate the hash code for that object.

For this basic reasoning, key objects are suggested to be IMMUTABLE. IMMUTABILITY allows you to get same hash code every time, for a key object. So it actually solves most of the problems in one go. Also, this class must honor the hashCode() and equals() methods contract.

This is the main reason why immutable classes like String, Integer or other wrapper classes are a good key object candidate.

Leave a comment