Quick revision
The short answer
Set.of and Map.of deliberately use an iteration order that changes from one JVM run to the next, so any code that depended on set order is now exposed, including JSON arrays, cache keys and ETags. The fix is to decide where order is part of a contract and use ordered types there, such as List, LinkedHashSet or a sorted collection, while consumers stop relying on undocumented order. We back that with review rules, order-insensitive tests, tests that catch hidden order dependencies, and clear release notes.
What to remember
In this answer, we saw that Set.of and Map.of intentionally randomize iteration order per JVM run, which exposed code that relied on set order in JSON arrays, cache keys and ETags. We decided where order is part of the contract and used List, LinkedHashSet or sorted collections there, asked consumers to compare sets rather than strings, added canonical-order tests and a review rule, and communicated the change through the shared library's release notes and a blameless incident note.
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.
Set.of and Map.of deliberately use an iteration order that changes from one JVM run to the next, so any code that depended on set order is now exposed, including JSON arrays, cache keys and ETags. The fix is to decide where order is part of a contract and use ordered types there, such as List, LinkedHashSet or a sorted collection, while consumers stop relying on undocumented order. We back that with review rules, order-insensitive tests, tests that catch hidden order dependencies, and clear release notes.
Why this question is asked
Immutable factory methods like Set.of are a good modernization, so teams adopt them widely, often through a shared library. The surprise comes later: responses that used to be byte-for-byte identical start changing after every restart. A response cache keyed on the body stops hitting, ETags change on every deploy, and consumer tests that compared JSON strings fail at random. Nothing is wrong with Set.of; it exposed an order dependency that was always there. Interviewers ask this to see whether we can find the real contract, fix it in the right place, and coordinate several teams without blame. In this answer, we will see why Set.of randomizes, trace how the order reaches JSON and caches, decide where order matters, fix producers and consumers, and add tests and communication so it does not repeat.
1Why Set.of Changes Its Order Between Runs
A set, by definition, has no order. HashSet happens to iterate in an order that depends on hash codes and table size, which for strings is stable across runs, so code quietly came to depend on it. The immutable collections returned by Set.of and Map.of (Java 9 and later) are implemented differently: they use a compact array with open addressing, and they mix a salt into the position of each element. The salt is chosen when the JVM starts, so iteration order differs between runs but stays fixed within one run.
The JDK designers did this on purpose. If the order is never stable, nobody can come to rely on it, and the implementation stays free to change. That is exactly the situation this team has walked into: code relied on an order that was never promised.
Notice that the change appears only across restarts. A unit test that serializes the set twice in the same JVM sees identical output, which is why the problem slipped through testing.
2How the Order Reaches JSON and the Cache
Jackson serializes a Set as a JSON array by iterating it, so the array order is the set's iteration order. A response such as {"roles":["viewer","admin","editor"]} after one restart becomes {"roles":["editor","viewer","admin"]} after the next. The data is the same, but the bytes are different.
Anything that treats the bytes as identity now breaks. A response cache keyed on a hash of the body, an ETag computed from the body, a signature over the payload, a deduplication step that compares serialized messages, and consumer tests that compare the whole JSON string all see a new value after every restart, and with several instances behind a load balancer, even between two requests.
6 messages in order. Play them, or step through them one at a time.
Nothing changed in the data, but every byte-based identity changed.
3Deciding Where Order Is Part of the Contract
The first decision is not technical: for each place, is order part of the contract or not? For an API response, the answer is in the API documentation. If roles are documented as a set, clients must not depend on order, but we may still want a stable order so that caching and ETags work. For cache keys, signatures and hashes, order is always part of the contract, because they compare bytes. For internal constants that nobody iterates in a visible way, order does not matter and Set.of is perfect.
Where order matters, we use a type that has one. A List.of keeps exactly the order we wrote. A LinkedHashSet keeps insertion order while still rejecting duplicates, and since Java 21 it is a SequencedSet. A TreeSet or a sorted copy gives a canonical order that does not depend on how the data was built, which is the best choice for cache keys and signatures.
For maps serialized as JSON objects, Jackson has SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, which sorts map entries by key. Using it globally is a quick stabilizer for objects, but there is no equivalent switch for sets, so arrays still need sorting where they are built.
4What Consumers Should Change
Consumers have their own part to fix. A test that compares a whole JSON string to an expected string is testing the serializer, not the contract. Consumer tests should parse the response and compare the roles as a set, or use an order-insensitive JSON comparison such as JSONAssert in lenient mode. Production consumer code should do the same: if the API says roles is a set, convert it to a set on arrival.
We should be fair in how we present this. The producer changed observable behaviour, so the producer should restore a stable order where it promised or implied one. But the consumers relied on something undocumented, and they should remove that reliance too, otherwise the next refactoring will break them again.
5Tests That Surface Hidden Order Dependencies
Because the order changes only between JVM runs, we need tests that see more than one order. A simple way is to run the serialization in separate test JVMs, for example two forked test runs in CI, and compare outputs. A more direct way is to test that the producer's output is canonical: build the same view from inputs in different insertion orders, including shuffled lists, and assert the JSON is identical.
We also add a review rule: Set.of and Map.of are welcome for constants and lookups, but any set that is serialized, hashed, signed or used to build a key must be converted to a list in a defined order first. Some teams enforce part of this with an ArchUnit rule or a custom check that flags Set-typed fields in response DTOs.
6Coordinating Across Teams
Since the change came through a shared library, its release notes should say plainly that some collections now iterate in a different order on each JVM start, which outputs are affected, and what consumers should check. For this incident, we restore stable ordering in the affected responses quickly, so caches and consumers recover, then give consumer teams a short window to make their tests and code order-independent.
Finally, we write a brief incident note that explains the root cause without blame: an undocumented order dependency, exposed by a correct library change. That note, plus the review rule, is what prevents the same discussion with the next team.
- Is the output compared as bytes (cache key, ETag, signature)?YesMake the order canonical: sortNoCheck the API contract
- Does the API document an order?YesUse List or LinkedHashSet in that orderNoSort anyway for stable caching
- Consumers compare as setsparse and compare, never compare raw strings
- Add review rule and canonical-order tests
- Announce in shared library release notes
5 steps in order. Play them, or step through them one at a time.
7Follow-up questions
Can we make Set.of iteration order deterministic with a JVM flag?
There is no supported option for that, and relying on one would defeat the purpose. The order is unspecified by contract. The right fix is to use a collection whose order is defined wherever order matters, rather than trying to freeze an implementation detail.
Is HashSet order stable then?
It is often the same between runs for strings and boxed numbers, because their hash codes are deterministic, but it is still unspecified and changes when the capacity changes or the JDK changes its hashing. For enums and objects without overridden hashCode, it depends on identity hash codes and can vary between runs. Code should not rely on it either.
Why not just turn every Set in DTOs into a TreeSet?
That works for comparable elements and gives a canonical order, and it is a reasonable default for response objects. The cost is that sorting happens on every insert and the elements must be comparable or need a comparator. Converting to a sorted List at the point of building the response is simpler and makes the order an explicit decision.
8Conclusion
In this answer, we saw that Set.of and Map.of intentionally randomize iteration order per JVM run, which exposed code that relied on set order in JSON arrays, cache keys and ETags. We decided where order is part of the contract and used List, LinkedHashSet or sorted collections there, asked consumers to compare sets rather than strings, added canonical-order tests and a review rule, and communicated the change through the shared library's release notes and a blameless incident note.
Open with
The root cause is that Set.of and Map.of intentionally use an iteration order that is randomized per JVM run, using a salt chosen at startup. Within one run the order is stable, which is why our tests passed, but after a restart the same set serializes to a JSON array in a different order.
Then, if they want more
Anything that treats the response bytes as identity then breaks: the response cache, ETags, signatures and consumer tests that compare whole JSON strings. The library change is correct; it exposed an order dependency that was never part of any contract. So first I would decide, place by place, where order is part of the contract.
For cache keys, ETags and signatures it always is, so those outputs must be canonical, for example a sorted list. For API responses I check what the API documents, and even when it is a set I would sort it so caching works.
Where order matters I use List, LinkedHashSet or a sorted collection, and I keep Set.of for constants and lookups. Consumers should parse arrays that the API calls sets and compare them as sets, using order-insensitive JSON assertions in tests.
To keep it from coming back, I add a review rule that serialized or hashed sets must be converted to a defined order, plus tests that build the same view from different insertion orders and assert identical output.
And I would put a clear note in the shared library's release notes and share a short blameless write-up with the affected teams.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 21, Java 9
- 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
- The Collections Framework, overview, java.util, package documentation
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 "After upgrading code to use Set.of and Map.of for constants, some services produce JSON...": https://scrivio-interview-library.netlify.app/java/sets/7855f03b71/