Quick revision
The short answer
HashMap never promised any iteration order, yet code and tests came to rely on the order Java 7 happened to produce, so when Java 8 changed the hash spreading and the bucket handling, that order changed and things broke. The lesson is that any behaviour enough people can observe becomes a contract in practice, whatever the specification says. I would require ordered types such as LinkedHashMap or TreeMap wherever order matters, shuffle unspecified orders in tests with tools such as NonDex, and build and test against new JDK releases, including early-access builds, long before an upgrade is due.
What to remember
In this answer, we saw that HashMap never specified iteration order, but code and tests depended on the Java 7 order, and Java 8's internal changes broke them. Widely observed behaviour becomes a contract in practice, so as consumers we should not rely on it and as producers we should expect others to. The practices I would require are ordered types such as LinkedHashMap and TreeMap wherever order matters, including JSON and test assertions, NonDex runs that shuffle unspecified orders, and regular builds against new and early-access JDKs, rolled out through the shared build template and the review checklist.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
HashMap never promised any iteration order, yet code and tests came to rely on the order Java 7 happened to produce, so when Java 8 changed the hash spreading and the bucket handling, that order changed and things broke. The lesson is that any behaviour enough people can observe becomes a contract in practice, whatever the specification says. I would require ordered types such as LinkedHashMap or TreeMap wherever order matters, shuffle unspecified orders in tests with tools such as NonDex, and build and test against new JDK releases, including early-access builds, long before an upgrade is due.
Why this question is asked
Every large Java upgrade has a story like this one. A team moves from Java 7 to Java 8, nothing in the release notes looks relevant, and then dozens of tests fail because a JSON string or a list of values comes out in a different order. The real cost is not those tests; it is the production code that also depended on the order and nobody noticed. Interviewers ask this at a senior level because the answer is not about HashMap at all. It is about how we treat specifications, how we make hidden assumptions visible, and how we prepare an organisation for upgrades. In this answer, we will recap what HashMap does and does not promise, see why the order changed, explain why unspecified behaviour becomes a contract anyway, and then set out the practices I would require, with how I would roll them out.
1A Quick Recap: What HashMap Promises About Order
The Javadoc of HashMap says plainly that it makes no guarantees as to the order of the map, and in particular that the order may not stay constant over time. Iteration simply walks the internal table from bucket 0 upwards and, inside each bucket, follows the chain of nodes. So the order we see depends on the hash of each key, the current table size and the order in which colliding keys were inserted.
None of those are part of the API. They are implementation details, free to change in any release, and the JDK developers changed several of them in Java 8.
2Why the Order Changed in Java 8
Java 8 rewrote much of HashMap. It replaced the older multi-step bit mixing with a simpler h ^ (h >>> 16), it began appending new nodes at the tail of a bucket instead of the head, and it splits buckets during a resize in a way that preserves their order. It also added tree bins for crowded buckets. Each of these is a reasonable internal change, and each can move a key to a different bucket or a different position within one.
So a test that built a HashMap with the keys "b", "a", "c" and compared its toString() against a string literal passed for years on Java 7 and started failing on Java 8, though nothing about the map's behaviour as specified had changed.
Notice that the first assertion is not testing our code. It is testing the JDK's private bucket layout. The second assertion tests what we actually care about.
3Unspecified Behaviour Becomes a Contract Anyway
There is a well-known observation in software, often called Hyrum's Law: with enough users, every observable behaviour of a system will be depended on by somebody, whatever the contract says. HashMap order is a textbook case. Developers saw a stable order, wrote JSON comparisons, CSV exports, cache keys built from map.toString(), and even business logic such as taking the first entry as the default, and all of it worked for years.
The specification was right and the users were wrong, but that does not help the team that cannot upgrade. The practical lesson for a leader is twofold. As consumers, we should treat anything not written in the contract as something that will change. As producers of our own libraries and APIs, we should expect our accidental behaviour to be relied on, and either document it, or make it visibly unstable so nobody can rely on it. The JDK itself took the second path later: the immutable collections from Set.of and Map.of randomise their iteration order with a seed chosen at JVM start-up, so a dependency on their order fails quickly instead of years later.
4Practice 1: Use an Ordered Type Wherever Order Matters
The first rule I would require is simple to state: if the order of a map or set matters to anyone, the type must say so. LinkedHashMap keeps insertion order, TreeMap keeps sorted order, and since Java 21 both are SequencedMap types with methods such as firstEntry(). That applies to production code and to tests.
Two places need special attention. The first is serialised output, such as JSON, where clients or snapshot tests may compare text; we either build it from an ordered map or configure the serialiser to sort keys (Jackson has an ORDER_MAP_ENTRIES_BY_KEYS feature, for example). The second is test assertions, which should compare maps and sets with equality, or use helpers such as AssertJ's containsExactlyInAnyOrder, rather than comparing strings.
5Practice 2: Shuffle Unspecified Orders in Tests
Rules in a document are not enough, because people do not know they are depending on an order until it changes. So I would make the dependency fail on purpose. NonDex, a research tool from the University of Illinois with Maven and Gradle plugins, runs the test suite with JDK methods whose specifications allow several behaviours, such as HashMap iteration, HashSet iteration and getDeclaredMethods(), returning shuffled results. A test that fails under NonDex but passes normally has a hidden order dependency.
We would not run it on every commit, since it reruns tests several times. A nightly or weekly job on the main branch, with failures turned into tickets for the owning team, finds these problems at our own pace instead of during an upgrade.
- Order matters to someone?code, JSON, testsYesUse LinkedHashMap or TreeMapNoHashMap is fine
- Nightly NonDex runshuffles
HashMapandHashSetorder - Test fails only when shuffled?YesHidden dependency: ticket to ownerNoNo action
- CI job on the next JDKearly-access builds
- Upgrade with a known, short list of changes
5 steps in order. Play them, or step through them one at a time.
6Practice 3: Test Against New JDKs Early
The order change was visible in Java 8 early-access builds months before the release. Teams that ran their tests on those builds found the problem while it was cheap. So I would require a CI job that builds and tests our main services on the next JDK release, starting with early-access builds from jdk.java.net, and that runs at least weekly. Failures on that job are not blockers for normal work, but each one gets an owner and a decision: fix our code, or report a genuine regression to the OpenJDK project, which runs a Quality Outreach programme for exactly this.
This turns an upgrade from a project with unknown scope into a list we have been shortening for months. With the six-month JDK release cadence and an LTS every two years, it is the difference between upgrading in a quarter and being stuck on an old release.
7Rolling It Out Without Stopping the Teams
I would not start by asking 40 teams to audit every HashMap. I would add the JDK early-access job and a NonDex run to the shared build template first, because they find real problems with no effort from the teams. I would add the ordered-type rule to the code review checklist and the testing guidelines, with a short write-up of this incident as the example. And I would track two numbers: open order-dependency findings and the age of the oldest unresolved early-access failure. When those trend towards zero, the next upgrade is mostly paperwork.
8Follow-up questions
Is it ever acceptable to depend on HashMap's order?
Not for anything that should still work after a JDK upgrade, a resize or a different insertion history. Even within one JDK, the order can change when the map grows or when keys are inserted in a different sequence. If the order is convenient but not required, the code should still be written so that any order is correct.
How do we find existing order dependencies without NonDex?
Run the tests with a different JDK, or change the map's initial capacity in a test build, and see what fails. Searching for assertions on toString() of maps and sets, and for code that takes the first element of a HashMap or HashSet iteration, finds many of the rest. NonDex is simply the systematic version of this.
What does this teach us about our own APIs?
That consumers will depend on whatever they can see. If our service returns a list whose order is not guaranteed, we should say so, and consider deliberately varying it in test environments, as the JDK does with Map.of, so that clients do not build on an accident.
9Conclusion
In this answer, we saw that HashMap never specified iteration order, but code and tests depended on the Java 7 order, and Java 8's internal changes broke them. Widely observed behaviour becomes a contract in practice, so as consumers we should not rely on it and as producers we should expect others to. The practices I would require are ordered types such as LinkedHashMap and TreeMap wherever order matters, including JSON and test assertions, NonDex runs that shuffle unspecified orders, and regular builds against new and early-access JDKs, rolled out through the shared build template and the review checklist.
Open with
I see this as a lesson about relying on behaviour that was never promised. HashMap's Javadoc says it makes no guarantee about order, but in Java 7 the order was stable, so tests compared map.toString to literals, JSON output was compared as text, and some production code took the first entry as a default.
Then, if they want more
Java 8 changed the hash spreading, moved to tail insertion and added tree bins, so the order changed and all of that broke even though HashMap still met its specification. That is Hyrum's Law: any behaviour enough people can observe becomes a contract whether we wrote it down or not. So I would require three things.
First, wherever order matters, in code, in serialised output and in test assertions, the type must say so: LinkedHashMap for insertion order, TreeMap for sorted order, and tests compare maps by equality rather than by string.
Second, I would add a scheduled NonDex run, which shuffles the order of HashMap, HashSet and similar unspecified results, so hidden dependencies show up as failing tests owned by a team. Third, a CI job builds and tests our services on the next JDK, including early-access builds, so upgrade problems are found months early.
I would roll these out through the shared build template and the review checklist, and track open findings until the upgrade becomes routine.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 8, Java 7, Java 21
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- java.util.HashMap, API documentation, The Collections Framework, overview
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "HashMap iteration order for some keys changed between Java 7 and Java 8, which broke...": https://scrivio-interview-library.netlify.app/java/hashmap-internals/9be8f75277/