☕ Java Intermediate

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

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.