Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Interview question

How does HashMap work internally in Java? Java में HashMap internally कैसे काम करता है?

Answer

HashMap stores key-value pairs in an array of buckets. A key's hashCode() determines which bucket it goes into, and equals() resolves collisions within that bucket.

put(key, value) flow:
1. Compute key.hashCode() → 2. Apply internal hash spreading function → 3. Map to a bucket index (hash % array length) → 4. If bucket empty, store node → 5. If occupied (collision), check equals() against existing keys, then append (or update if key matches)
Map<String, Integer> map = new HashMap<>();
map.put('apple', 10);
map.put('banana', 20);

// get() follows the same hashCode -> bucket -> equals() process
Integer value = map.get('apple');  // 10

// Collisions - two different keys can land in the same bucket
// if their hashCode() values collide; HashMap resolves this by
// storing entries as a linked list (or a balanced tree since Java 8
// when a bucket has 8+ entries, for better worst-case performance)

// Java 8+ resizing: default capacity 16, load factor 0.75
// When size exceeds capacity * loadFactor, the table doubles and rehashes

// A poor hashCode() implementation (e.g. always returning the same value)
// makes ALL keys collide into one bucket, degrading HashMap to O(n) lookups
class BadKey {
    public int hashCode() { return 1; }  // terrible - all keys collide
}

HashMap key-value pairs को buckets के array में store करता है। Key का hashCode() यह तय करता है कि वो किस bucket में जाएगी, equals() collisions resolve करता है।

put(key, value) flow:
1. key.hashCode() compute → 2. Hash spreading function → 3. Bucket index पर map → 4. खाली हो तो store → 5. Collision हो तो equals() check करके append/update
Map<String, Integer> map = new HashMap<>();
map.put('apple', 10);
map.put('banana', 20);

Integer value = map.get('apple');  // 10

// Collisions - अलग keys same bucket में जा सकती हैं
// HashMap linked list (या Java 8+ में 8+ entries पर tree) से resolve करता है

// Java 8+ resizing: default capacity 16, load factor 0.75

class BadKey {
    public int hashCode() { return 1; }  // सभी keys collide होंगी
}

Was this answer clear?