Thursday, 9 October 2014

HashMap structure

This small article talks about the implementation details of an HashMap.

A HashMap uses a hashtable data structure to store key value pairs. Its implementation encapsulates only one collection: an array of Map.Entry objects.

Each Map.Entry object is a simple linked list containing a key object, a value object and a reference to the next Map.Entry object.

To find a value object in the HashMap using “get(key)”, the implementation calculates first an index using the key object’s hashcode, as follows:

index = keyObject.hashcode() mod table.size.

This index is then used to retrieve the Map.Entry from the array of Map.Entry objects.

Once the Map.Entry is found, as many key objects can have the same hashcode, it loops through each Map.Entry object and compare their key’s equalities.



It is recommended to set a value to “initialCapacity” by using the constructor HashMap(int initialCapacity). This will limit the re-size of the map improving its performance as the number of entries in the map would be less likely to exceed the product of the load factor and the current capacity.

See the implementation of a HashMap:
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/HashMap.java