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
- hashCode() is calculated for the key.
- Hash is converted into index → (n-1) & hash.
- If bucket empty → store entry.
- If collision → use equals() to check duplicate.
- 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