Video in progress

Strong Middle 🧺 Collections

If you print a HashMap with small Integer keys, the keys come out looking sorted. Why, and what happens if you rely on it?

Integer.hashCode() is the number itself, and the bucket is chosen with hash & (n - 1). If the keys are smaller than the table size, each one lands in the bucket with its own number, and iteration goes in bucket order, so the result looks sorted. That is an accident: once the keys grow, the order breaks.

📖 Answer

Map<Integer, String> m = new HashMap<>();
for (int k : new int[]{5, 1, 9, 3}) m.put(k, "v" + k);
System.out.println(m.keySet());   // [1, 3, 5, 9]

m.put(17, "v17");
System.out.println(m.keySet());   // [1, 17, 3, 5, 9] — 17 & 15 = 1

HashMap iteration walks the table from bucket 0 to the end. In a table with 16 buckets, 17 also lands in bucket 1 and comes out after 1. With large ids like 100_000 the order gets completely scrambled.

Why this is dangerous: a developer sees the keys come out in order in a test or with local data, and the code starts to rely on it: "the first element is the smallest id", "the report rows are sorted on their own". On prod the ids are in the millions and the order is random. It hurts most in tests: with a small fixture the test always passes, and with real data the result is different.

With String keys this kind of "order" doesn't show up, so the illusion appears mostly with numeric keys.

My rule is simple: if I need order, I say it with the type, TreeMap (by key) or LinkedHashMap (by insertion), or I sort explicitly before output. In code review, if I see code taking the "first" entry from a HashMap with iterator().next(), I ask about it right away.