DEV Community

Sharath Kumar
Sharath Kumar

Posted on

How HashMap Works Internally in Java 8?

A HashMap in Java is a data structure used to store key–value pairs and provides very fast operations (O(1) average time) for insertion and retrieval.

Java 8 introduced important internal improvements to make HashMap more efficient and prevent performance degradation.


🔹 Basic Internal Structure

Internally, HashMap uses:

👉 Array of Nodes (Buckets)

Each element is stored inside a bucket based on the hash value of the key.

Array (Bucket Index)
[0] → Node
[1] → Node → Node
[2] → null
[3] → TreeNode (Red-Black Tree)
Enter fullscreen mode Exit fullscreen mode

🔹 Step-by-Step Working

1️⃣ Hash Calculation

When you insert data:

map.put("Java", 100);
Enter fullscreen mode Exit fullscreen mode
  • hashCode() of key is calculated
  • Hash is converted into bucket index
index = (n - 1) & hash
Enter fullscreen mode Exit fullscreen mode

where n = array size.


2️⃣ Bucket Selection

The calculated index decides where the entry will be stored.


3️⃣ Handling Collisions

If multiple keys map to the same bucket:

✅ Java 7 → LinkedList
✅ Java 8 → LinkedList + Red-Black Tree (optimization)


4️⃣ Tree Conversion (Java 8 Improvement)

If entries in one bucket exceed 8 nodes:

👉 LinkedList converts into Red-Black Tree.

Benefits:

  • Search time improves from O(n)O(log n).

If size reduces below 6, it converts back to LinkedList.


5️⃣ Resizing (Rehashing)

When HashMap becomes 75% full (default load factor = 0.75):

  • Capacity doubles
  • Elements are rehashed
  • New bucket positions calculated

🔹 Internal Node Structure

static class Node<K,V> {
    final int hash;
    final K key;
    V value;
    Node<K,V> next;
}
Enter fullscreen mode Exit fullscreen mode

🔹 Important Points (Interview Focus)

✅ HashMap allows one null key
✅ Not thread-safe
✅ Faster read/write operations
✅ Uses hashCode() + equals() internally
✅ Java 8 uses Red-Black Tree for heavy collisions


🔹 Time Complexity

Operation Average Worst Case
Put O(1) O(log n)
Get O(1) O(log n)

🔹 Real-Time Example

Used in:

  • Caching systems
  • Database indexing
  • Session management
  • Configuration storage

🚀 Promotional Content

Learn core concepts like HashMap internals, collections, and real-time backend development in No 1 Java Real Time Projects Online Training in ammerpet.

Top comments (0)