A HashMap (or hash table) is a data structure that maps keys to values for highly efficient lookup. There are a number of ways to implement this data structure. This post is about the simple implementation of HashMaps in Java using an array of a linked list.

So, let's first define a class representing a node of a linked list as:

Inserting Element

First, compute the key's hash code, which will usually be an int. The two different objects could have the same hash code, as there may be an infinite number of elements and a finite number of ints.

Then, calculate the index in the array using hash code using modulo as hashCode (key) % array_length. Here, two different hash codes could map to the same index.

Get the linked list at this index calculated above. Store the element in this index. The use of a linked list is important because of collisions: you could have two different keys with the same hash code or two different hash codes that map to the same index.

Time Complexity

Since different keys can be mapped to the same index, there is a chance of collision. If the number of collisions is very high, the worst case runtime is O(n), where n is the number of keys. However, we generally assume a good implementation that keeps collisions to a minimum, in which case the lookup time is O(1).

Conclusion

This post illustrated how HashMap (or HashTable) can be implemented with an array-based linked list. You can take a look more examples on Cracking the Coding Interview by Gayle Laakmann McDowell.

The source code for all example presented above is available on GitHub.