How HashMap Works?

Short Answer:
HashMap stores key-value pairs using hashing. It uses hashCode() to find the bucket and equals() to resolve collisions.

Detailed Explanation:
HashMap internally uses an array of buckets (Node[] table). Each bucket stores entries as LinkedList (Java 7) or LinkedList + Red-Black Tree (Java 8+).


Internal Working Steps

  1. hashCode() is calculated for the key.
  2. Hash is converted into index → (n-1) & hash.
  3. If bucket empty → store entry.
  4. If collision → use equals() to check duplicate.
  5. If bucket size > 8 → convert to Red-Black Tree (Java 8).

equals() and hashCode() Contract

Short: If two objects are equal, their hashCode must be equal.

  • If equals() returns true → hashCode() must be same.
  • If hashCode same → equals() may or may not be true.
  • Always override both together.
@Override
public int hashCode() {
    return id;
}

@Override
public boolean equals(Object obj) {
    if(this == obj) return true;
    if(!(obj instanceof Student)) return false;
    Student s = (Student) obj;
    return this.id == s.id;
}

How Resizing Works

Default capacity = 16 Default load factor = 0.75 Resize happens when:

Size > Capacity × Load Factor

Example: 16 × 0.75 = 12 When 13th element inserted → capacity doubles to 32.

  • New array created.
  • All entries rehashed.
  • Time-consuming operation.

ConcurrentHashMap Internal Working

Short: Thread-safe version of HashMap without full locking.

Java 7 → Segmented locking Java 8+ → CAS (Compare and Swap) + synchronized on bucket level

  • No null key allowed.
  • Better performance in multi-threaded apps.
  • Reads are mostly non-blocking.

HashMap vs Hashtable vs ConcurrentHashMap

Feature HashMap Hashtable ConcurrentHashMap
Thread Safe No Yes (full lock) Yes (partial lock)
Null Key 1 allowed Not allowed Not allowed
Performance Fast Slow High in multi-thread
Introduced Java 1.2 Java 1.0 Java 1.5

Important Interview Points

  • Time Complexity → O(1) average.
  • Worst case → O(n).
  • Treeify threshold = 8.
  • Untreeify threshold = 6.
  • HashMap not synchronized.

0 comments

Leave a comment