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.
Previous
What is the difference between ArrayList and LinkedList?
Next
What is the difference between HashMap and HashTable in Java?
More Java Questions
View all →- Intermediate What is the Java Collections Framework?
- Intermediate What is the difference between ArrayList and LinkedList?
- Intermediate What is the difference between HashMap and HashTable in Java?
- Intermediate What is the difference between HashMap and LinkedHashMap?
- Intermediate What is the difference between HashSet and TreeSet?