Lesson 4.4 · Hashing
Hashing Pitfalls
Arrays as keys, mutable keys, boxed comparisons and missing keys: the bugs that make correct-looking hash code fail.
8 min
Think of it like this
If you change the name on a cloakroom ticket after handing in your coat, the attendant computes a different hook and can't find it. Keys must not change while they're in a map.
1.Four classic traps
Arrays as keys: int[] uses object identity for equals and hashCode, so two arrays with the same numbers are different keys. Use List<Integer> or a String.
Mutable keys: changing an object after putting it in a map changes its hash code, so the map can't find it again.
Boxed comparisons: map.get(a) == map.get(b) compares Integer references; use .equals or unbox.
Missing keys: map.get(k) returns null; unboxing null throws. Use getOrDefault.
import java.util.*;
public class Main {
public static void main(String[] args) {
Set<int[]> arrays = new HashSet<>();
arrays.add(new int[]{1, 2});
System.out.println(arrays.contains(new int[]{1, 2})); // false: identity
Set<List<Integer>> lists = new HashSet<>();
lists.add(List.of(1, 2));
System.out.println(lists.contains(List.of(1, 2))); // true: content
}
}Output
false
trueRemember
- Never use arrays as keys.
- Never change a key while it's in a map.
- Compare boxed values with equals; use getOrDefault.
Common mistakes
Set<int[]>for de-duplicating pairs.count.get(x) + 1when x might be missing.