Internal Working of Hashmap

Internal Working of HashMap in Java

๐Ÿ” Internal Working of HashMap in Java

✅ Step-by-Step Explanation

1. Adding a Key-Value Pair

map.put("name", "John");

We start by adding a key-value pair to the HashMap.

2. Hash Code Generation

Java computes a hash code for the key using:

int hash = key.hashCode(); // "name".hashCode()

3. Converting Hash to Array Index

To reduce collision risk, it computes the index in the underlying array:

index = (hash & (array.length - 1));

4. Bucket Check

If the bucket at the index is empty, the entry is stored directly. If not, a collision has occurred.

5. Collision Handling

On collision, Java uses:

  • LinkedList chaining for simple conflicts
  • Red-Black Tree (since Java 8) if bucket size > 8 and capacity > 64
Bucket[5] → ("id", 101) → ("name", "John")

6. Retrieving a Value

map.get("name");

HashMap recalculates the hash and index, then looks for the matching key in the bucket.

7. Resizing

When the size exceeds 75% of capacity (load factor = 0.75), the array is resized and entries are rehashed.

๐Ÿ“Œ Quick Summary

Step What Happens
1Calculate key’s hashCode()
2Convert hash to index using bitwise AND
3Store entry in calculated bucket
4Handle collisions with LinkedList or Tree
5Resize when 75% full and rehash all keys

๐Ÿงช Example Usage

HashMap<String, String> map = new HashMap<>();
map.put("a", "apple");
map.put("b", "banana");
map.put("c", "carrot");
    

For each key:

  • Hash code is generated
  • Converted to an array index
  • Stored in corresponding bucket

๐Ÿง  Powered by Passion, Compiled with Precision

© 2025 JavaVerse Blog — Crafted by Janki Patel

๐Ÿ’ป All things Java • Tutorials • Insights • Best Practices

Comments

Popular posts from this blog

๐Ÿ”ฅ Java Exception and Error Handling

Understanding How OOP Concepts Work with Real-Life Examples

๐ŸŒฟ⚙️ Spring Boot Simplified