HashMap Custom Implementation in Java

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

  1. First, we will create static class Node<K,V> inside CustomHashMap<K,V> class

Article content


2. Then we need to add the fields and constructors of CustomHashMap<K,V> class-

Article content


3. Now we need an array of type Node<K,V> and a hash function

Article content

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.

Article content

5. Next will be to create put() method:

Article content

6. get() method:

Article content

7. Lastly we will add toString() method:

Article content

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.

Like
Reply

To view or add a comment, sign in

More articles by Harshit Anand

  • How Caching Works in Springboot?

    Hey Java Devs 👋. In this article, we will see how Caching works in Springboot.

    1 Comment
  • What are Load Balancers?

    We are using the internet on daily basis. Popular websites like Netflix, Amazon, Hotstar, and Facebook receive millions…

Others also viewed

Explore content categories