How HashMap Works Internally in Java

How HashMap Works Internally in Java

In this Java tutorial, we are going to see how HashMap internally works in JAVA. We will have a look at what Java 8 made changes to the internal working of Hashmap to make it faster.

Take a look at this article that explains how Hashmap works in Java, including how it calculates the index of a bucket and how other internals work.

In this article, we are going to see how HashMap internally works in java. Also, we will have a look at what Java 8 made changes on the internal working of Hashmap to make it faster.

What is Hashmap and Hashing in java?

How Hashmap works Internally in Java is majorly dependent upon the Hashing Principle. So, Before going to learn how HashMap works internally in java, lets first understand what is HashMap and hashing.

HashMap :

A HashMap is a map used to store mappings of key-value pairs. Also, it works on the Principle of Hashing.

Hashing Principle :

Simply, Hashing is a method used to produce an integer value from an object and this integer value known as the hash value. In HashMap, the key object is used for Hashing.

Internal Struture of the HashMap in java

For internal working of HashMap, HashMap maintains an array of bucket, each bucket is a linked-list and linked list is a list of nodes wherein each node contains key-value pair.

Note : After Java 8, a bucket can be a linked-list or a binary tree depending upon the Threshold. We will discuss this later in the post.

Array of Bucket or Bucket Table :

The array of bucket is also known as the Bucket Table of the HashMap in Java. HashMap uses hashing method to calculate the index of array or which Bucket is going to be used. Internally Bucket array defined as

Internal Representation of Bucket Array

// Each Node of the Array is a Bucket
Node<K,V>[] table;

Bucket :

A bucket is a linked list of nodes where each node is an instance of class Node<K,V>. The key of the node is used to generate the hash value and this hash value is used to find the bucket from Bucket Table.

Note: When two or more keys generate the same hash, then it called a Hash Collision. In that case, the new node adds to the linked list. We will discuss more this later in the post that how HashMap works internally in java to handle Hash Collision.

Node :

Each node of the Linked List is an instance of class Node<K,V> and actually store key-value pair that we are storing in the HashMap. This class is an static inner class of HashMap class and it implements the Map.Entry<K,V> interface. The representation of this Node as :

Inner Static Node class of HashMap

static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Node<K,V> next;
}
  • final int hash : hash value of the key
  • final K key : Key of the node
  • V value : Value of the node
  • Node<K,V> next : Pointer to the next node present in the bucket or linked-list

How Hashmap Calculate the Index of Bucket in java?

To understand how HashMap works internally in Java, we must know about how the HashMap calculates the index of the bucket. Till now, we know the internal structure of HashMap, that HashMap maintains an array of the bucket. But when we store or retrieve any key-value pair, HashMap calculates the index of the bucket for each and every operation.

The Key object is used to calculate the index of the bucket. By using this key, hash value is calculated using hash(key) private method of HashMap.

Note: hash(key) method is a private method of HashMap that returns the hash value of the key, also if the hash value is too large then converts it into a smaller hash value.

But what will happen, if hash value of Key Object returns the integer that is greater than the size of the array i.e., hash(key) > n, then ArrayOutOfBoundsException could be raised. To handle this situation, HashMap reduces the hash value between 0 and n-1 using an expression :

Index Calculating Expresssion

index = hash(key) & (n-1)

Now, this index value is generated is used by HashMap to find bucket location and can never generate any Exception as the index value always from 0 to n-1.

Role of hashCode() and equals() in HashMap

The hashcode() and equals() have a major role in how HashMap works internally in java because each and every operation provided by the HashMap uses these methods for producing results.

hashCode() :

The hashCode() method puts a major impact on how HashMap works internally in java as it is used to find the bucket location from the Bucket Table.

For any given key, the hash(key) private method of HashMap used to calculate the hash value. Internally, the hash(key) method uses hashCode() method of the key object to get the hash value.

Note :

a) If the key is null then the hash value returned by the hash(key) private method of HashMap will be 0.

b) If the key.hashCode() is too large then hash(key) private method of HashMap converts it into smaller number.

equals() :

The equals() method also puts an impact on how HashMap works internally in java as it is used to check whether the key is present or not in the Bucket after the bucket is determined from the Bucket Table or Bucket Array.

Or In other words, When the bucket location is calculated then each node of the bucket is traversed and compared with the key object to check whether the key is present or not in the Bucket.

So, we can say hashCode() is used to find which bucket and equals() is used for key uniqueness.

How put() method of Hashmap works internally in java?

The put() method is a method of HashMap used to store key-value pair.

Syntax of put() method

hashmap.put(key, value);

Working of put() method :

1. The key is used to calculate the hash value by calling private hash(key) method, internally hash(key) method call hashCode() method of key.

hash = hash(key);

Note : HashMap can store one null value as the key. In that case, the hash value returned by the hash(key) method will be 0 and 0th bucket location will be used.

2. The above hash is reduced from 0 to n-1 to calculate the index of bucket (where n is the size of an array of the bucket).

index = hash & (n-1);

3. A new instance of Node<K,V> class is created.

Node<K,V> newNode = new Node(hash , key , value , null); // null for next pointer

4. The index of the bucket is used to fetch the bucket, then the new node is added to the fetched bucket.

java programming developer

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

How to Install OpenJDK 11 on CentOS 8

What is OpenJDK? OpenJDk or Open Java Development Kit is a free, open-source framework of the Java Platform, Standard Edition (or Java SE).

Top 10+ Java Development Companies in India & Developers Reviews 2020 – TopDevelopers.co

A thoroughly researched list of top 10 Java development companies in India with ratings & reviews to help find the best java developers around India.

Hire Java Developers Team | Java Developer India - Developers.dev

.DEV is a leading java Developer agency. Our offshore Java Developer Staff offers robust cross-platform java development services at an affordable rate. 1000+ Sucessful Projects, 100+ Happy Customers, 650+ Professionals, 60% Saving on Project Cost

How long does it take to develop/build an app?

This article covers A-Z about the mobile and web app development process and answers your question on how long does it take to develop/build an app.

3 Best Programming Languages for Java Developers

In this article, I’ll share 3 JVM Programming languages Java programmers can learn and why you should learn them. Being a Polyglot developer is of good quality and often valued highly in interviews.