HashMap Custom Implementation in Java
Hey Folks 👋
In this article, we will learn how to implement your custom hashmap in Java. This is a very popular interview question. For writing the custom implementation of HashMap you must have the intuition of why HashMap as a Data Structure came into the picture and how does it works internally.
This article assumes that you already have an understanding of HashMap and its internal workings. I'll only show code snippets and thought processes to create custom HashMap in Java. However, you are free to use any language.
In case you are not aware, you can watch this video -https://youtu.be/jjW8w8ED3Ns?si=cx2Ha1jOpQl735Uv
Thought Process:
A HashMap internally uses an array of type Node<K,V>. Each node will have a key, a value and a Node<K,V>.
Let's have the class CustomHashMap<K,V>. This class will have a DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR, capacity, loadFactor, an array of type Node<K,V>
Node<K,V> will be a static class inside the CustomHashMap class. It will have a key, a value and Node<K,V>
Let's dive into the code then. We will use a bottom-up approach (meaning we will write small pieces first which all together will constitute the CustomHashMap<K,V> class)
Code Snippets
2. Then we need to add the fields and constructors of CustomHashMap<K,V> class-
Recommended by LinkedIn
3. Now we need an array of type Node<K,V> and a hash function
4. Next we will ensureCapacity() method. ensureCapacity() method is used to make sure that the hash map can hold more data and if not, it will resize the hash map.
5. Next will be to create put() method:
6. get() method:
7. Lastly we will add toString() method:
That's it. Your custom hashmap implementation is ready to use. Just combine all the pieces :)
Run the code on your machine and validate the output.
As always this post is open for feedback. I'm still learning 🙂
See you next time 😁👋
in ensureCapacity(), don't you think 2 different existing keys can have the same newIndex? If yes, there can be collision in newTable as well inside while loop. Also, the node's next should be set to null after newTable[newIndex] = node.
Nice explanation
✌