HashMap
HashMap stores key-value pairs in buckets chosen by hashCode. Average get and put are O(1). Keys must have a correct equals/hashCode pair, and the map is not thread-safe.
Detailed Explanation
A map is a lookup table: given a key, find the value. HashMap places each key in a bucket hash & (length-1). In that bucket it keeps a list, or a tree of nodes if the bucket grows large (Java 8+). A good hash spreads keys, so most buckets are short, and a lookup compares a handful of keys.
null is allowed as one key and as any value. get returns null both for a missing key and for a key whose value is null. containsKey distinguishes those cases. put replaces and returns the previous value. putIfAbsent, computeIfAbsent, and merge are the methods that avoid a separate contains plus put race in single-threaded code.
Iteration order is not the insertion order and not the sort order. It can change when the table resizes. If you need insertion order, use LinkedHashMap. If you need sorted keys, use TreeMap. If threads share the map, use ConcurrentHashMap; a plain HashMap can infinite-loop on concurrent resize in older JDKs and can lose entries in current ones.
Capacity and load factor control resizes. The default load factor is 0.75. When size > capacity * 0.75, the table doubles and entries rehash. If you know you will put 10_000 entries, new HashMap<>(16384) avoids a chain of resizes. The cost of a huge initial capacity is unused memory.
You reach for HashMap as the default map. You do not use it as a cache without bounds (it grows until the heap dies). You do not use mutable keys: if hashCode changes after insert, the entry is lost. Records and strings are safe keys. Arrays are not; they use identity equals.
The cost of a poor hashCode is everything in one bucket: O(n) lookups and, after treeification, extra memory. The cost of iterating keySet plus get is two hash lookups; iterate entrySet. The cost of assuming order is a flaky test.
Code Examples
import java.util.HashMap;
import java.util.Map;
public class Counts {
public static void main(String[] args) {
Map<String, Integer> counts = new HashMap<>();
for (String word : new String[] {"a", "b", "a"}) {
counts.merge(word, 1, Integer::sum);
}
System.out.println(counts.get("a")); // prints: 2
System.out.println(counts.containsKey("c")); // prints: false
System.out.println(counts.get("c")); // prints: null
}
}import java.util.HashMap;
import java.util.Map;
public class Compute {
public static void main(String[] args) {
Map<String, String> env = new HashMap<>();
String port = env.computeIfAbsent("PORT", key -> "8080");
System.out.println(port); // prints: 8080
System.out.println(env.get("PORT")); // prints: 8080
}
}Common Gotchas
Mutating a key after `put` loses the entry
`get` hashes the new state and looks in the wrong bucket.
`get` returning `null` is ambiguous
use `containsKey` or `getOrDefault`.
`HashMap` is not thread-safe
concurrent `put`s corrupt the table. Use `ConcurrentHashMap`.
Iteration order is unspecified
do not assert it in tests.