Back to Study Material Java

HashMap in Java

HashMap is the most widely used implementation of the Map interface in Java. It stores key-value pairs in an array of buckets using hashing. When you call ...

HashMap in Java

How HashMap Works Internally

HashMap is the most widely used implementation of the Map interface in Java. It stores key-value pairs in an array of buckets using hashing. When you call put(key, value), Java computes the hash code of the key, applies a secondary hash function to reduce collisions, and places the entry in the corresponding bucket. If two keys land in the same bucket, HashMap uses a linked list or, since Java 8, a balanced tree (red-black tree) when the bucket exceeds eight entries, improving worst-case lookup from O(n) to O(log n).

HashMap allows one null key and multiple null values. It does not guarantee any order of its entries. The default initial capacity is 16 buckets, and the load factor is 0.75. When the number of entries exceeds capacity times load factor, HashMap resizes by doubling the bucket array and rehashing all entries, which is an expensive operation to trigger often.

HashMap<String, String> capitals = new HashMap<>(); capitals.put("France", "Paris"); capitals.put("Japan", "Tokyo"); capitals.put(null, "Unknown"); System.out.println(capitals.get("Japan")); // Tokyo

For iterating, the entrySet() approach is cleanest:

for (Map.Entry<String, String> entry : capitals.entrySet()) { System.out.println(entry.getKey() + " -> " + entry.getValue()); }

HashMap is not thread-safe. If you need concurrent access, use ConcurrentHashMap instead of wrapping HashMap with Collections.synchronizedMap(), as ConcurrentHashMap provides better performance under concurrent reads.

When designing keys for a HashMap, always override both equals() and hashCode() consistently. If two objects are equal by equals(), their hash codes must be identical; otherwise lookups will silently fail.

Interview tip: A classic question is what happens if you use a mutable object as a HashMap key and then change it. The answer is that the key's hash code changes, making it impossible to retrieve the original value, effectively losing the entry.