Friday, 4 April 2025

 

πŸ”₯ Top 15+ Tricky HashMap Interview Questions (With Smart Answers)

Whether you're preparing for interviews at Amazon, Google, TCS, Infosys, Wipro, or Capgemini, or simply leveling up your Java skills, understanding HashMap internals is a must. Let's explore the trickiest HashMap interview questionsβ€”with crisp, smart answers that impress interviewers.


πŸš€ 1. Can HashMap have null keys and null values?

🧠 Trick: Many think null is never allowed.

βœ… Answer:

  • Yes, 1 null key is allowed.

  • Multiple null values are allowed.


HashMap<String, String> map = new HashMap<>(); map.put(null, "value"); // βœ… null key map.put("a", null); // βœ… null value

πŸš€ 2. What happens when you insert duplicate keys?

🧠 Trick: Interviewers expect you to explain key replacement.

βœ… Answer:
The latest value overrides the old value for the same key.


map.put("fruit", "apple"); map.put("fruit", "mango"); System.out.println(map.get("fruit")); // Output: mango

πŸš€ 3. Is HashMap thread-safe?

🧠 Trick: If you say yes β€” that’s a red flag.

βœ… Answer:
❌ No, it is not thread-safe. Use:

  • Collections.synchronizedMap() (slower, locks whole map)

  • ConcurrentHashMap (preferred in multi-threading)


πŸš€ 4. Can two unequal objects have the same hash code?

🧠 Trick: This is about collision handling.

βœ… Answer:
Yes! It's called a hash collision.


System.out.println("FB".hashCode()); // 2236 System.out.println("Ea".hashCode()); // 2236

Java handles collisions using:

  • Linked List (Java 7)

  • Red-Black Tree (Java 8+)


πŸš€ 5. What happens internally when put() is called?

🧠 Trick: They want step-by-step internal flow.

βœ… Answer (Java 8):

  1. Compute hash using hashCode()

  2. Map hash to bucket index

  3. Check if key exists using equals()

  4. If exists β†’ replace value

  5. If not β†’ create new Node

  6. If collisions > 8 β†’ convert bucket to Red-Black Tree


πŸš€ 6. What is the load factor?

🧠 Trick: Misunderstanding load factor leads to wrong resizing logic.

βœ… Answer:
Load factor = threshold to resize

  • Default = 0.75f

  • Resize happens when:
    current size β‰₯ capacity * loadFactor


πŸš€ 7. What is rehashing?

🧠 Trick: Interviewers want to test your understanding of resizing.

βœ… Answer:
When capacity threshold is crossed, HashMap creates a new array (double size) and repositions all existing keys (rehashing).


πŸš€ 8. Can HashMap key be mutable?

🧠 Trick: Many devs unknowingly use mutable objects as keys.

βœ… Answer:
Technically yes, but it's a bad practice.
If a key’s hashCode changes after insertion, you won't be able to retrieve the value.


πŸš€ 9. Difference between HashMap, TreeMap, and LinkedHashMap?

FeatureHashMapTreeMapLinkedHashMap
Ordering❌ No orderβœ… Sortedβœ… Insertion order
Null Keyβœ… One❌ Not allowedβœ… One
Thread-safe❌ No❌ No❌ No

πŸš€ 10. What is treeification in Java 8?

🧠 Trick: This tests Java 8 internal knowledge.

βœ… Answer:
If one bucket has more than 8 entries and capacity β‰₯ 64, Java 8 converts the bucket into a Red-Black Tree β†’ improves lookup to O(log n)


πŸš€ 11. What’s the worst-case time complexity of get() and put()?

ScenarioJava 7Java 8
Best case (no collision)O(1)O(1)
Worst case (collision)O(n)O(log n)

πŸš€ 12. What causes ConcurrentModificationException?

🧠 Trick: Simple-looking question, but many fail it.

βœ… Answer:
Modifying a HashMap while iterating it using for-each loop (without Iterator’s remove()).

for (Map.Entry entry : map.entrySet()) { map.put("x", "y"); // ❌ Throws ConcurrentModificationException }

πŸš€ 13. Can initial capacity be set to a large value like Integer.MAX_VALUE?

βœ… Answer:
You can, but it’s risky:

  • Might throw OutOfMemoryError

  • Wastes memory if not filled


πŸš€ 14. Why should hashCode() and equals() be overridden for custom keys?

🧠 Trick: Real-world trap question.

βœ… Answer:
HashMap uses:

  • hashCode() β†’ to find bucket

  • equals() β†’ to find key in that bucket

If not overridden, keys won’t match, leading to unexpected behavior.


πŸš€ 15. Can a HashMap have two keys with same hash code?

βœ… Answer:
Yes. HashMap handles collisions using chaining.


Key1.hashCode() == Key2.hashCode() // true Key1.equals(Key2) // false β†’ both exist in same bucket

No comments:

Post a Comment