☕ Java Intermediate

What is HashMap in Java and how does it work internally?

Why Interviewers Ask This

This tests whether you can apply Java knowledge to real-world scenarios. Interviewers are looking for clarity of thought and evidence that you've encountered this in production code.

Answer

HashMap stores key-value pairs and allows one null key and multiple null values. Internally, it uses an array of "buckets" (an array of linked lists/trees). When you call put(key, value), Java calls key.hashCode() to compute the hash, then uses it to determine which bucket to store the entry in. If two keys have the same bucket (hash collision), they are stored in a linked list (or a red-black tree if the list exceeds 8 elements — Java 8 optimization). Average time complexity for get/put is O(1); worst case (all keys collide) is O(n). HashMap is not thread-safe — use ConcurrentHashMap for concurrent access.

Pro Tip

Back up your answer with a specific project or situation. Saying 'In my last Java project, I used this when...' immediately makes your answer more credible and memorable.