Quick revision
The short answer
Arrays.asList(internalArray) hands callers a write-through view of the library's own array, so a caller's sort() or set() reorders and rewrites the library's internal state. We fix the API by returning an immutable copy (List.of or List.copyOf) or, when callers really need a live view, an unmodifiable view, and we document which one it is. Then we look for the same pattern across the codebase with static analysis and a review checklist, and we decide the copy cost on purpose for very large arrays.
What to remember
In this answer, we saw that returning Arrays.asList(internalArray) exposes a write-through view, so a caller's sort or set changes the library's private data. We fixed the API by building an immutable copy once and returning it, or by returning an unmodifiable view when a live view is really intended, and by documenting whether each returned collection is a copy or a view and whether it can be modified. We then found similar cases with static analysis and a search, added a review checklist rule, and weighed the copy cost for very large arrays so that the choice is made on purpose.
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.
Arrays.asList(internalArray) hands callers a write-through view of the library's own array, so a caller's sort() or set() reorders and rewrites the library's internal state. We fix the API by returning an immutable copy (List.of or List.copyOf) or, when callers really need a live view, an unmodifiable view, and we document which one it is. Then we look for the same pattern across the codebase with static analysis and a review checklist, and we decide the copy cost on purpose for very large arrays.
Why this question is asked
Bugs like this are hard to find because the code that breaks is not the code that is wrong. The library looks fine in its own tests, the caller only sorted a list it was given, and yet a third service sees its data in a different order on the next call. Interviewers use this scenario to see whether we can explain the root cause, fix the API without breaking every caller, and turn one incident into a habit for the whole team. In this answer, we will reproduce how the caller changes the library, look at the options for returning the data and what each costs, write the fixed API, and then plan how to find and prevent similar cases.
1A Quick Recap: Why Arrays.asList Leaks
Arrays.asList does not copy. It returns a small fixed-size list, java.util.Arrays.ArrayList, whose only storage is a reference to the array we passed in. Any call that replaces elements, such as set(), sort() or replaceAll(), writes straight into that array. Only operations that change the size, such as add() and remove(), are refused.
When the array is a private field of a library class, returning that view is the same as returning the field itself. The private keyword protects the reference, not the contents, so encapsulation is broken even though the code compiles cleanly.
2Reproducing the Problem
Here is a cut-down version of the library and the caller from the question.
5 messages in order. Play them, or step through them one at a time.
The view is a door into the private array, and any caller can walk through it.
Notice that the caller did nothing unusual. List.sort is a normal operation, and for Arrays.ArrayList it is implemented by sorting the backing array in place. Every other caller, and the library itself, now sees the caller's order. If the library used that order for something, for example a binary search or a priority list, it is now quietly wrong.
3The Options for Returning the Data
We have three reasonable shapes for the return value, and they differ in what callers can do and what it costs us.
An immutable copy, made with List.of(names) or List.copyOf(Arrays.asList(names)), gives callers a snapshot they cannot modify. Changes to the library's array after the call are not visible, and calls to sort() or set() on the result throw UnsupportedOperationException. It costs one array of references per call, and List.of rejects null elements, so we must be sure the array has none.
An unmodifiable view, made with Collections.unmodifiableList(Arrays.asList(names)), copies nothing. Callers cannot modify it, but they see later changes the library makes to its own array. This is the right choice only when a live view is part of the contract, for example a configuration that is reloaded in place.
A defensive mutable copy, new ArrayList<>(Arrays.asList(names)), lets callers sort and edit freely without touching the library. It is friendly, but it hides intent: callers cannot tell whether modifying the list does something, and we pay for a copy every time.
| Return | Caller can modify? | Sees later changes? | Cost per call |
|---|---|---|---|
Arrays.asList(array) | set and sort, writes through | yes | none |
Collections.unmodifiableList(view) | no | yes | one small wrapper |
List.copyOf / List.of | no | no | copy of n references |
new ArrayList<>(view) | yes, own copy | no | copy of n references |
| copy built once, cached in a field | no | no | copy once, then none |
4Fixing the API
For a class whose data does not change after construction, the best fix is to make the immutable copy once, in the constructor, and return the same list every time. Callers get safety and we pay nothing per call.
Notice that the caller who wanted a sorted list now gets a clear exception the first time it runs, in its own code, rather than a silent change in someone else's. The fix to the caller is a one-line copy.
This is a behaviour change for existing callers, so we treat it like one. Some caller may have depended on modifying the list. We search for callers, run their tests against the new version, and announce the change in the release notes, even though the old behaviour was a bug.
5Documenting Copies and Views
Much of this bug comes from an unstated contract. The Javadoc of every method that returns a collection should answer two questions: is this a copy or a view, and can the caller modify it? Phrases such as Returns an immutable snapshot or Returns an unmodifiable view that reflects later changes take one line and save the next team an incident. The JDK itself does this; for example, Map.keySet is documented as a view backed by the map.
6Reviewing Similar Cases Across the Codebase
One incident usually means the pattern exists elsewhere. We can find it mechanically. SpotBugs reports exposing internal representation through its EI_EXPOSE_REP and EI_EXPOSE_REP2 patterns, which cover returning or storing a mutable array or collection field; Error Prone and Sonar have similar rules (check the exact rule names for your tool version). A simple search for return Arrays.asList( and for getters that return array or collection fields directly also finds most cases in an afternoon.
To keep it from coming back, we add a line to the review checklist: any public method that returns or stores a collection or array must copy it or wrap it, and say which in its Javadoc. Records deserve a special mention, because a record component of type List or array is returned as is by its accessor; a compact constructor that calls List.copyOf fixes that.
7When Copying Is Too Expensive
Copying is not free. If the array holds 50 million elements and names() is called on every request, a copy per call would allocate hundreds of megabytes per second. In that case we copy once and cache, as above, or return an unmodifiable view and document that it is live. If callers need only part of the data, an API that returns one element or a range, or a stream, avoids exposing the whole array. Whichever we choose for a large array, we write the choice and the reason into the Javadoc so the next reviewer does not undo it.
8Follow-up questions
Is Collections.unmodifiableList enough on its own?
It stops callers from changing the list, but it is still a view. If the library changes its array later, callers see the change, and code that kept the list from an earlier call can observe data changing underneath it. That is correct when a live view is the contract, and surprising when callers expected a snapshot. For data that should never change, an immutable copy is the safer default.
Should the library also copy arrays that callers pass in?
Yes, for the same reason. If a constructor stores a caller's array directly, the caller can keep a reference and change the library's state later. Copying at the boundary, for example with List.of(names) or names.clone(), closes both doors: what comes in and what goes out.
Why not just return the array clone?
names.clone() is a correct defensive copy, but arrays cannot be made read-only, so every call must clone again, and callers get a type that invites modification. Returning an immutable List lets us copy once and share the result safely.
9Conclusion
In this answer, we saw that returning Arrays.asList(internalArray) exposes a write-through view, so a caller's sort or set changes the library's private data. We fixed the API by building an immutable copy once and returning it, or by returning an unmodifiable view when a live view is really intended, and by documenting whether each returned collection is a copy or a view and whether it can be modified. We then found similar cases with static analysis and a search, added a review checklist rule, and weighed the copy cost for very large arrays so that the choice is made on purpose.
Open with
The root cause is that Arrays.asList returns a view, not a copy. It is a fixed-size list backed by the array, so set and sort write straight into the library's private array, and every other caller sees the change.
Then, if they want more
The private field protected the reference, not the contents. To fix the API, I would make the defensive copy once, at construction, with List.of or List.copyOf, store that immutable list and return it every time. Callers that try to sort it now get UnsupportedOperationException in their own code and make their own sorted copy.
If a live view really is part of the contract, I would return Collections.unmodifiableList over the array and document that it reflects later changes. Either way, the Javadoc should say whether the collection is a copy or a view and whether it can be modified.
Because some callers may rely on the old behaviour, I would ship it with release notes. Then I would look for the pattern elsewhere: SpotBugs has expose-representation checks, a search for return Arrays.asList and for getters that return array fields finds most cases, and the review checklist gets a rule about copying collections at API boundaries, including record components.
For very large arrays I would avoid a copy per call by caching the copy or offering narrower accessors, and document that decision.
About this answer
- Last updated
- 12 November 2026
- 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 "A shared library method returns Arrays.asList(internalArray) to callers, and a caller's...": https://scrivio-interview-library.netlify.app/java/lists/b3901f5d85/