Implement HashMap in Java

Abhinay Gupta
3 min readJul 13, 2021

to implement following functions in HashMap:

put(), get(), remove(), size(),keySet(),containsKey()

We will be using Arrays of LinkedList . Each linked List will represent a bucket. After hashing of keys, the key will be added to its corresponding bucket.

Our Node will look like this .

private class HMNode{
K key;
V value;
HMNode(K key, V value){
this.key=key;
this.value=value;
}
}

Now we will see the basic attributes of our HashMap Class:

public static class HashMap<K,V>{
private class HMNode{
K key;
V value;
HMNode(K key, V value){
this.key=key;
this.value=value;
}
}
private int size=n;
private LinkedList<HMNode>[] buckets; //--> length of bucket= N
public HashMap(){
size=0;
initbuckets(8);
}
private initbuckets(int N){
buckets= new LinkedList[N];
for(int i=0;i<N;i++){
buckets[i] =new LinkedList();
}
}
}

put()

first we need to find in which bucket our key is present, then after finding it we will find the index of our key in that bucket. and if the key is already present we update the value of node else we add a new node and increment size by 1. We also need to check that our lambda doesn’t become more than threshold , if it does we call rehash() function. rehash() creates 2N buckets and put all the nodes in these new buckets.

--

--

Abhinay Gupta

Exploring personal growth, tech, and culture through engaging storytelling | Inspiring and connecting with readers worldwide.