100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Java

HashMap in Java

Learn how HashMap stores key-value pairs using hashing, its null-key rules, and why iteration order is not guaranteed.

Collections FrameworkIntermediate9 min readJul 7, 2026
Analogies

1. Introduction

HashMap is the most widely used implementation of the Map interface. It stores data as key-value pairs and uses hashing to provide average O(1) time complexity for get() and put() operations.

🏏

Cricket analogy: A scorer who can instantly find any player's stats by jersey number instead of scanning the whole team sheet is working like a HashMap, using hashing to jump straight to the right bucket in near-constant time.

Internally, HashMap uses an array of 'buckets', where each key's hashCode() determines which bucket it lands in. Keys that hash to the same bucket are chained together (as a linked list, or a balanced tree if a bucket grows large in Java 8+).

🏏

Cricket analogy: A stadium's numbered stand system routes ticket holders to the right block by seat-hash, and if too many fans crowd one block, ushers form an organized queue (or, in a packed final, a managed grid) — like HashMap's buckets chaining into a linked list or, when crowded, a balanced tree.

2. Syntax

text
Map<String, Integer> map = new HashMap<>();
map.put("apple", 10);
map.put(null, 100);      // one null key allowed
map.put("banana", null); // multiple null values allowed
map.get("apple");
map.containsKey("apple");
map.remove("apple");

3. Explanation

HashMap allows exactly one null key and any number of null values, unlike its legacy counterpart Hashtable, which disallows both. get() and put() run in average O(1) time thanks to hashing, but can degrade to O(n) in the worst case (e.g., many hash collisions) — Java 8+ mitigates this by treeifying buckets with 8+ colliding entries.

🏏

Cricket analogy: A HashMap is like a scoring system that allows exactly one 'no player named' placeholder entry but many blank scores, unlike the old-school Hashtable-style scorebook that forbids both; lookups are usually instant but slow to a full page-flip if too many entries collide, which Java 8+ fixes by reorganizing crowded pages into a sorted index.

HashMap does NOT guarantee any iteration order — the order can even change between runs or after resizing. HashMap is also not synchronized/thread-safe; for concurrent access use ConcurrentHashMap, or the older, fully synchronized (and slower) Hashtable.

🏏

Cricket analogy: HashMap is like a scorer who calls out results in whatever order the ledger happens to land, not by innings order, and shouldn't be trusted with two scorers writing at once without a coordinated system like ConcurrentHashMap, or the older, slower fully-locked Hashtable.

Contrast: Hashtable (legacy) is synchronized and disallows null keys/values. ConcurrentHashMap (modern) is thread-safe with better concurrency than a synchronized Hashtable, and also disallows null keys.

4. Example

java
import java.util.*;

public class HashMapDemo {
    public static void main(String[] args) {
        Map<String, Integer> inventory = new HashMap<>();
        inventory.put("Laptop", 25);
        inventory.put("Mouse", 100);
        inventory.put(null, 5); // allowed: one null key

        System.out.println("Get Laptop: " + inventory.get("Laptop"));
        System.out.println("Get null key: " + inventory.get(null));
        System.out.println("Contains 'Mouse': " + inventory.containsKey("Mouse"));

        inventory.put("Mouse", null); // allowed: null value
        System.out.println("Mouse value: " + inventory.get("Mouse"));
        System.out.println("Size: " + inventory.size());
    }
}

5. Output

text
Get Laptop: 25
Get null key: 5
Contains 'Mouse': true
Mouse value: null
Size: 3

6. Key Takeaways

  • HashMap stores key-value pairs and uses hashing for average O(1) get/put.
  • Allows exactly one null key and multiple null values.
  • Iteration order is not guaranteed and may change over time.
  • Not synchronized — use ConcurrentHashMap for thread-safe access.
  • Java 8+ treeifies heavily-collided buckets to avoid worst-case O(n) degradation.

Practice what you learned

Was this page helpful?

Topics covered

#Java#JavaProgrammingStudyNotes#Programming#HashMapInJava#HashMap#Syntax#Explanation#Example#DataStructures#StudyNotes#SkillVeris