Friday, 4 April 2025

 

🚀 Top Tricky HashMap Questions & Answers for MNC Interviews

🌟 1. Can we store a null key in HashMap and ConcurrentHashMap?

✅ Answer:

  • HashMap allows one null key.

  • ConcurrentHashMap ❌ does not allow null keys.

Example:

Map<String, String> map = new HashMap<>();
map.put(null, "value");  // ✅ Works fine

Map<String, String> concurrentMap = new ConcurrentHashMap<>();
concurrentMap.put(null, "value");  // ❌ Throws NullPointerException

🌟 2. What happens when two keys have the same hashCode()?

✅ Answer:

This is called a hash collision.

  • Java stores both keys in the same bucket but differentiates them using equals().

  • In Java 7, it used Linked List chaining.

  • In Java 8, if collisions exceed 8, it converts the linked list to a Red-Black Tree to improve O(n)O(log n).


🌟 3. What happens if hashCode() is different but equals() is true?

✅ Answer:

This should never happen because Java assumes:

🚨 If two objects are equal (equals() returns true), they must have the same hashCode().
Otherwise, Java will store them in different buckets, breaking the contract.

Example:

@Override
public int hashCode() { return 123; }  // ❌ Wrong: Every object gets the same hash
@Override
public boolean equals(Object obj) { return true; } // ❌ Bad practice

🔴 This can cause data inconsistency and difficult debugging issues.


🌟 4. What is the worst-case time complexity of HashMap.get()?

✅ Answer:

Scenario Java 7 (O(n)) Java 8 (O(log n))
Best case O(1) (Direct bucket access) O(1)
Worst case O(n) (All elements in same bucket, linked list traversal) O(log n) (Tree traversal in Red-Black Tree)

🚩 Real-world trap: If your hashCode() implementation is bad (returns same value for all keys), performance degrades to O(n).


🌟 5. Can a HashMap have duplicate keys?

✅ Answer:

📝 No. If you insert a duplicate key, it overwrites the existing value.

Map<String, String> map = new HashMap<>();
map.put("fruit", "apple");
map.put("fruit", "banana");
System.out.println(map.get("fruit"));  // Output: banana (replaced apple)

🌟 6. What happens if put() is called during iteration?

✅ Answer:

It throws ConcurrentModificationException.

for (Map.Entry<String, String> entry : map.entrySet()) {
   map.put("newKey", "newValue");  // ❌ ConcurrentModificationException
}

📝 How to avoid?
👉 Use Iterator.remove() instead of map.put() during iteration.
👉 Use ConcurrentHashMap if multi-threading is needed.


🌟 7. What is the default capacity of a HashMap?

✅ Answer:

  • Default capacity: 16

  • Default load factor: 0.75

  • Resize happens when size reaches 16 * 0.75 = 12

📝 How to avoid frequent resizing?
🚀 Initialize HashMap with correct size using:

Map<String, String> map = new HashMap<>(128);

🌟 8. What happens if two threads modify a HashMap at the same time?

✅ Answer:

💀 Data corruption or infinite loop (Java 7)
💀 Lost updates (Java 8)

📝 Solution?
👉 Use ConcurrentHashMap for multi-threading.
👉 Or wrap with Collections.synchronizedMap() (slower).


🌟 9. How does ConcurrentHashMap work internally?

✅ Answer:

👉 Before Java 8: Used segments (mini hash tables)
👉 In Java 8+:

  • No segments

  • Uses bucket-level locking

  • Uses CAS (Compare-And-Swap) for atomic updates

  • Avoids full map locking → much faster


🌟 10. Can we use a mutable object as a HashMap key?

✅ Answer:

🚨 Bad idea! If key’s hashCode() changes, it gets lost in the map.

Example:

class Key {
    int id;
    Key(int id) { this.id = id; }
    @Override
    public int hashCode() { return id; }
}
Map<Key, String> map = new HashMap<>();
Key key = new Key(10);
map.put(key, "value");

key.id = 20;  // ❌ Changing key's hashCode!
System.out.println(map.get(key)); // Output: null ❌ LOST ENTRY!

📝 Solution: Use immutable objects as keys (like String or Integer).



No comments:

Post a Comment