Skip to main content

How null key is stored in HashMap Java 8+?

how null key is store in java hashmap

 

In Java, HashMap has specific behavior when it comes to handling null keys and values:

null Key Handling in HashMap

  • A HashMap allows one null key.

  • Internally, the null key is treated specially and stored in the first bucket (index 0).

  • If you insert another entry with null as the key, it will overwrite the previous one.

null Values

  • A HashMap allows multiple entries with null values.

๐Ÿ” Example:

import java.util.HashMap;

public class NullKeyExample {
public static void main(String[] args) {
HashMap<String, String> map = new HashMap<>();

map.put(null, "first"); // First null key
map.put("one", "1");
map.put(null, "second"); // Overwrites the previous null key

System.out.println(map.get(null)); // Outputs: second
System.out.println(map); // Outputs: {null=second, one=1}
}
}

⚠️ Notes:

  • If you use other Map implementations (e.g., TreeMap or Hashtable), behavior differs:

    • TreeMap throws NullPointerException if you use null as a key (unless a custom Comparator supports it).

    • Hashtable does not allow null keys or values.

๐Ÿง  How HashMap Internally Handles null Key

When you call:

map.put(null, "value");

HashMap internally routes it differently than regular keys.

๐Ÿ”ง Behind the Scenes (Java 8+):

Here's roughly what happens in the put() method of HashMap:

public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
๐Ÿ”Ž hash(key):
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
  • If the key is null, it returns a hash of 0.

So the null key always hashes to bucket index 0.

๐Ÿ“Œ Special Handling in putVal():

In putVal():

  1. If the key is null, it directly checks index 0.

  2. If a node with null key is already present, it updates the value.

  3. Otherwise, it adds a new Node at index 0.

if (tab[i = (n - 1) & hash] == null)
tab[i] = newNode(hash, key, value, null);

Since hash = 0 for null key, i = 0, so it stores it in bucket 0.

๐Ÿ“ฅ Retrieval with get(null)

Similarly, in get():

public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
Again, hash(null) returns 0, and it searches bucket 0.
It compares keys using == for null, avoiding equals() calls.
๐Ÿงช Quick Test
map.put(null, "value1");
System.out.println(map.get(null)); // Outputs: value1
map.put(null, "value2");
System.out.println(map.get(null)); // Outputs: value2
Each new put(null, ...) just overwrites the old one at index 0.  

Comments

Popular posts from this blog

25+ Spring Data JPA Interview Questions with Answers, Explanations & Use Cases

  ๐Ÿ“˜ Spring Data JPA Interview Questions (with Answers, Explanations & Use Cases) 1. What is JPA and how is it related to Spring Data JPA? Answer: JPA (Java Persistence API) is a Java specification for managing relational data. Spring Data JPA is a part of Spring Data that simplifies JPA usage by reducing boilerplate code. Use Case: Persisting Java objects (like User ) to a relational database without writing SQL. 2. What are the key annotations used in JPA? Answer: @Entity , @Table , @Id , @GeneratedValue , @Column , @ManyToOne , @OneToMany , etc. Explanation: These annotations map Java objects to database tables and relationships. Use Case: Creating a User entity with an auto-generated ID and fields mapped to table columns. 3. What is the difference between JPA and Hibernate? Answer: JPA is a specification; Hibernate is an implementation of that specification. Use Case: Using Hibernate as the default JPA provider in Spring Boot. 4. How do you define a p...

How to Send Emails in Spring Boot Using SMTP (With and Without Attachments)

Sending emails is a common requirement in modern web applications — for things like user registration, password resets, or notifications. In this tutorial, we’ll walk through how to send emails in a Spring Boot application using SMTP , specifically with Gmail’s SMTP server , and demonstrate how to send both plain emails and emails with attachments . ๐Ÿ“บ Video Demo If you prefer watching over reading, here’s a full demo of this tutorial in action: ๐Ÿ“ GitHub Repo  Want the complete working code? Clone the GitHub link provided below which contains all the source code. Source Code GitHub Link: https://github.com/TheDipDeveloper/Spring-Boot-Sending-Email ๐Ÿงฐ Prerequisites Java 17 or above Maven Spring Boot 3.x A Gmail account  ๐Ÿš€ Step 1: Add Spring Boot Mail Dependency First, add all the required dependency on pom.xml file < dependencies > < dependency > < groupId >org.springframework.boot</ groupId > < artifactId >spring...

Create a Real-World Banking System with Spring Boot 3, JPA, MySQL & Postman

Are you looking to build a real-world project using Spring Boot and MySQL? In this tutorial, we'll walk you through creating a complete Banking Service REST API that supports full CRUD operations, money transfers, deposits, and withdrawals. Whether you're preparing for interviews or enhancing your portfolio, this hands-on project will give you practical experience with Spring Boot 3, Spring Data JPA, and RESTful API design. In this post, you'll learn how to build a Banking Service REST API using: ✅ Spring Boot 3.x ✅ Java 17 ✅ MySQL ✅ Postman for API testing ✅ IntelliJ IDEA ✅ GitHub Repo : https://github.com/TheDipDeveloper/Banking-Service-Application-REST-Api By the end, you'll have a complete backend application that supports: Creating bank accounts Fetching account data Deposits and withdrawals Transferring funds between accounts Deleting accounts ๐Ÿ› ️ Tech Stack Java 17 Spring Boot 3.x Spring Data JPA MySQL Lombok ...