How hashmap works in Java. My style of learning.
We aggregate and tag open source projects. We have collections of more than one million projects. Check out the projects section.
This is the most frequently asked questions in the interview. Googling will throw many links related to this topic. How to learn the implementation of hash map? My style of learning using open source learning technique.
Download Java code from openjdk
. Open the source of HashMap.Java. The file is available under src\java\util folder. Check out how it is implemented.
- HashMap is not synchronized. There is no synchronized keyword available in source.
- It accepts null value. There is a explicit check in get and put function, which checks for null and creates a separate value for it.
- Every object in Java has hashcode. HashMap has a hash function which generates hash value of hashcode. This value is used as index to retrieve object from the bucket.
- It stores both key and value in the bucket as Map.Entry.
- While retrieving, it identifies the bucket using the hash value and loops through all the values. It returns the value which matches the key. Since it is storing both key and value, it will retrieve the correct object even two object generates the same hash code.
- If the size of the bucket reaches the threshold then it resizes the bucket and transfers the current objects to it. This operation is expensive so plan ahead for better capacity by passing it as constructor argument.
This method of learning is called Open Source Learning Technique. If you follow, it will certainly make you independent. Googling will not always give you correct result. You need to open up 10 links instead, spend some time in reading code.
Happy learning !!