Hashing pitfalls in Java
24 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A HashMap or HashSet solution can have the right algorithm and still fail on large test cases—or silently return wrong answers—because of four Java-specific pitfalls: boxed Integer reference equality, mutable or array keys, hash collisions, and unnecessary autoboxing.
== on boxed Integer values
A frequency map holds Integer objects, so comparing two of its values with == is a trap.
Example 1 · Demonstrating the == trap on boxed Integer counts at 127 vs. 128
import java.util.HashMap;import java.util.Map;
public class BoxedIntegerEqualityTrapDemo { public static void main(String[] args) { Map<String, Integer> mapA = new HashMap<>(); Map<String, Integer> mapB = new HashMap<>();
mapA.put("small", 127); mapB.put("small", 127); mapA.put("large", 128); mapB.put("large", 128);
System.out.println("127 with == : " + (mapA.get("small") == mapB.get("small"))); System.out.println("128 with == : " + (mapA.get("large") == mapB.get("large"))); System.out.println("128 with .equals : " + mapA.get("large").equals(mapB.get("large"))); System.out.println("128 with intValue: " + (mapA.get("large").intValue() == mapB.get("large").intValue())); }}127 with == : true 128 with == : false 128 with .equals : true 128 with intValue: true
What this code does
- 127 lies inside Java's [-128, 127] Integer cache, so both maps reference the exact same Integer instance.
- 128 creates two distinct Integer objects on the heap, causing == to return false while .equals() and .intValue() return true.
Because Java generics only accept reference types, a frequency map is declared as Map<Character, Integer> or Map<Integer, Integer>. Comparing two values returned by .get(...) with ==, as in window.get(c) == need.get(c), is a bug once a count reaches 128.
Both .get(c) calls return Integer object references, so == compares object identity (memory addresses), not numerical equality! By the Java Language Specification, Integer.valueOf(int) is guaranteed to cache boxed Integer instances only for the range -128 to 127 (in the standard JVM, unless configured otherwise). For counts ≤ 127, your unit tests pass because both maps point to the same cached Integer object; as soon as a test case has count 128 or 200, two distinct Integer objects are allocated and == evaluates to false!
Fix: Always compare two boxed Integer (or Long) values using .equals(...), .intValue(), or by assigning one side to a primitive int first.
- Integer == Integer compares object references (only guaranteed true for -128 .. 127).
- int == Integer unboxes the Integer to a primitive int and compares values safely.
- map1.get(k).equals(map2.get(k)) or map1.get(k).intValue() == map2.get(k).intValue() works for all int values.
Mutable keys
A hash map picks the bucket for a key from its hashCode() at insertion time, so a key must not change afterwards.
Example 2 · Array key bug vs. Java 17 record key and mutable key bug
import java.util.ArrayList;import java.util.HashSet;import java.util.List;import java.util.Set;
public class MutableAndArrayKeyTrapDemo { record Coord(int r, int c) {}
public static void main(String[] args) { // 1. Raw int[] array as Set element fails value equality: Set<int[]> rawArraySet = new HashSet<>(); rawArraySet.add(new int[]{1, 2}); System.out.println("rawArraySet contains [1, 2]: " + rawArraySet.contains(new int[]{1, 2}));
// 2. Java 17 record as Set element works cleanly: Set<Coord> recordSet = new HashSet<>(); recordSet.add(new Coord(1, 2)); System.out.println("recordSet contains (1, 2): " + recordSet.contains(new Coord(1, 2)));
// 3. Mutating a List AFTER adding it to a Set loses the entry: Set<List<Integer>> listSet = new HashSet<>(); List<Integer> mutable = new ArrayList<>(List.of(10, 20)); listSet.add(mutable); mutable.add(30); System.out.println("listSet contains mutated: " + listSet.contains(mutable)); }}rawArraySet contains [1, 2]: false recordSet contains (1, 2): true listSet contains mutated: false
What this code does
- new int[]{1, 2} uses Object identity hashCode/equals, so a second new int[]{1, 2} is not found.
- record Coord(int r, int c) is immutable and implements value-based equals and hashCode automatically.
- Mutating a List after inserting it into a HashSet changes its hashCode without moving it to the new bucket.
Two major bugs follow from this:
- Mutating a key after insertion: If you put a
List<Integer>or custom object into aHashSetand then modify it (e.g.,list.add(99)), itshashCode()changes, but the object is still sitting in its old bucket! Looking up the modified list searches the new bucket (false), and looking up the old value failsequals(false)—the entry becomes an unreachable phantom. - Using Java arrays (
int[],char[]) as keys: In Java, arrays do not overrideObject.equalsorObject.hashCode! Two separatenew int[]{1, 2}arrays have different identity hash codes and are never.equals(...). For composite keys in Java 17, use an immutablerecord(e.g.,record Pair(int r, int c) {}),String, orList.of(...).
Predict the output
Arrays as map keys
Work out the printed value.
What does this code print?
record Point(int x, int y) {} declared right inside your method automatically generates value-based equals, hashCode, and toString with immutable fields!Many collisions slow a map down (simplified) & Using an array when the range is small
Simplified model of hash collisions: A HashMap is backed by an array of buckets. Ideally, keys spread evenly across buckets so each lookup inspects 1–2 entries (O(1) expected time).
Example 3 · Using an offset array int[2001] when values lie in [-1000 .. 1000]
public class OffsetArrayVsMapDemo { public static boolean uniqueOccurrences(int[] arr) { // Constraint: -1000 <= arr[i] <= 1000, arr.length <= 1000 int OFFSET = 1000; int[] freq = new int[2001]; for (int x : arr) { freq[x + OFFSET]++; } boolean[] seenCount = new boolean[arr.length + 1]; for (int c : freq) { if (c > 0) { if (seenCount[c]) { return false; } seenCount[c] = true; } } return true; }
public static void main(String[] args) { int[] a = {1, 2, 2, 1, 1, 3}; System.out.println("[1,2,2,1,1,3] unique counts: " + uniqueOccurrences(a)); int[] b = {-3, 0, 1, -3, 1, 1, 1, -3, 10, 0}; System.out.println("b unique counts: " + uniqueOccurrences(b)); }}[1,2,2,1,1,3] unique counts: true b unique counts: true
What this code does
- Because -1000 <= arr[i] <= 1000, adding OFFSET = 1000 maps every number into a valid array index 0 .. 2000.
- Both the value frequencies and the occurrence uniqueness check run in O(n) time with zero object allocations.
If thousands of distinct keys produce the same bucket index (a hash collision), they pile up in the same bucket. In Java 7 and earlier, every bucket was a linked list, so n colliding keys degraded lookup to O(n) per operation (O(n²) total). Since Java 8 (and in Java 17), when a bucket chain reaches 8 nodes (and table capacity is ≥ 64), HashMap converts that bucket into a balanced red-black tree, bounding worst-case lookup to O(log n) when keys implement Comparable (such as Integer, Long, String).
Even so, HashMap<Integer, Integer> still boxes primitives, allocates Node objects, and hashes keys. Whenever your keys come from a small, known integer range—such as ASCII chars 0..127, lowercase letters 0..25, remainders 0..k-1, or values 0..1000—use a direct primitive array int[]! An int[] has zero collisions, zero boxing, and guaranteed worst-case O(1) array indexing.
- Lowercase English letters 'a'..'z' -> int[26] indexed by c - 'a'.
- Standard ASCII characters -> int[128] indexed by c.
- Remainders modulo k -> int[k] indexed by Math.floorMod(sum, k).
- Small bounded integers [-1000 .. 1000] -> int[2001] indexed by val + 1000.
Next step
Check your understanding
10 quick questions