Scrivio Interview library
ScenarioIntermediate7 min read · updated 12 November 2026

A service passes its internal List<OrderLine> to a pricing library, and later finds lines modified and reordered. Another class returns its internal Map from a getter. Explain the risk in terms of pass-by-value of references and how you design APIs to avoid it.

Passing a List or returning a Map does not hand out a copy of the data; it hands out a copy of the reference, so the pricing library and the getter's callers are working on the very same collection the class owns. Any add, remove or sort they do changes our internal state. We avoid it by passing and returning immutable copies or read-only views, building value types as immutable records with defensive copies, and stating in the API who owns and may change each collection.

Why this question is asked

Bugs where data changes 'by itself' are some of the most expensive to find, because the code that changed it is far from the code that notices. A pricing library that sorts our order lines to find the cheapest one, or a caller that removes an entry from a map it got from a getter, will silently corrupt our object. Interviewers ask this to see whether we connect the Java rule, references are passed by value, with API design, which is where it really matters. In this answer, we will reproduce both leaks, explain them in terms of shared references, and then look at copies, unmodifiable views, immutable records and ownership rules, including what each costs for large collections.

1A Quick Recap: What a Method Really Receives

Java copies every argument into the called method. For a List, the value that gets copied is a reference, a pointer to the one list object on the heap. After the call, our field and the library's parameter both point to the same ArrayList. Nothing in Java stops the library from calling add, remove, set or sort on it, and every change is made to our list.

A getter that returns a field works the same way in the other direction. return prices; returns the reference stored in the field, so the caller now holds a pointer to our internal map. Encapsulation, the idea that a class controls its own state, is broken without any warning from the compiler.

2Reproducing Both Leaks

Here is a small version of the service from the question.

Java
record OrderLine(String sku, int qty, long priceCents) {}
class Order {
private final List<OrderLine> lines = new ArrayList<>();
private final Map<String, Long> discounts = new HashMap<>();
void price(PricingLibrary lib) { lib.apply(lines); } // hands out our list
Map<String, Long> getDiscounts() { return discounts; } // hands out our map
}
// inside the library, written by another team
void apply(List<OrderLine> lines) {
lines.sort(Comparator.comparingLong(OrderLine::priceCents)); // reorders OUR list
lines.removeIf(l -> l.qty() == 0); // deletes from OUR list
}
order.getDiscounts().clear(); // the caller just wiped the order's discounts
Step throughOne list, two owners
OrderArrayList linesPricingLibrary
creates and stores the reference
apply(lines): copies the reference
sort(...) reorders the shared list
removeIf(...) deletes lines
later reads lines: changed and reordered

5 messages in order. Play them, or step through them one at a time.

Passing the list copies the pointer, not the elements.

Notice that neither the library nor the caller did anything illegal. The library was given a mutable list and treated it as its own. The caller was given a map and changed it. The real fault is in our API: it published internal state through shared references.

3Copies Versus Unmodifiable Views

The first tool is to hand out something the receiver cannot change. Java gives us two kinds, and they behave differently.

Java
List<OrderLine> internal = new ArrayList<>(List.of(new OrderLine("A", 1, 500)));
List<OrderLine> copy = List.copyOf(internal); // immutable copy
List<OrderLine> view = Collections.unmodifiableList(internal); // read-only view
copy.add(new OrderLine("B", 1, 100)); // UnsupportedOperationException
view.add(new OrderLine("B", 1, 100)); // UnsupportedOperationException
internal.add(new OrderLine("C", 2, 300));
System.out.println(copy.size()); // 1: the copy is a snapshot
System.out.println(view.size()); // 2: the view shows our later changes
Ways to share a collection
OptionReceiver can change it?Sees our later changes?Cost
return the fieldyesyesnothing, but state leaks
Collections.unmodifiableListnoyes (a view)one wrapper object
List.copyOfnono (a snapshot)copies n references
immutable by designnonothing changescopy once at creation

List.copyOf creates a new immutable list with the same elements, so it is a snapshot that never changes again. It also refuses null elements with a NullPointerException, which is often a useful check. Collections.unmodifiableList creates no copy at all; it wraps our list in a read-only window. The receiver cannot change it, but it sees every change we make later, and if it keeps the view and iterates while we modify the list, it can get a ConcurrentModificationException.

So for passing data to a library that might keep it, a copy is the safe choice. For a getter on a large collection where callers only read immediately, a view is cheaper because it costs one small wrapper object instead of copying every element. Map.copyOf and Collections.unmodifiableMap give the same two options for maps.

4Making the Value Type Immutable

The strongest fix is to stop having mutable state to protect. If an order's lines never change after it is built, we can make the type a record and copy the list once, in the compact constructor, the record constructor form without a parameter list that runs before the fields are assigned.

Java
record PricedOrder(String id, List<OrderLine> lines) {
PricedOrder {
lines = List.copyOf(lines); // defensive copy, also rejects nulls
}
}
var source = new ArrayList<>(List.of(new OrderLine("A", 1, 500)));
var order = new PricedOrder("o-1", source);
source.clear(); // the caller changes its own list
System.out.println(order.lines().size()); // 1: the record kept its own copy
order.lines().add(null); // UnsupportedOperationException

Notice that the copy protects us in both directions. The caller cannot change the record through the list it passed in, because the record holds its own copy, and nobody can change the record through the accessor, because the copy is immutable. The accessor can then return the field directly with no further copying, which is the benefit of immutability by design: we pay for one copy when the object is created instead of a copy on every call.

Copying still has a cost. For a list of 100,000 lines, List.copyOf allocates an array of 100,000 references, which is cheap once but noticeable if done on every getter call in a hot loop. That is exactly why designing the type as immutable, so it is copied once, beats defensive copying in every method.

5Writing Ownership Into the API

Some code must stay mutable, for example a builder that collects lines, or a library that is meant to sort in place for speed. Then the API should say so. A parameter documented as 'the list is not modified and not retained' tells callers they can pass their own list. A method named sortInPlace(List) tells them it will change it. A constructor that keeps a reference should say whether it copies. Good names and short Javadoc sentences remove most surprises, and returning List from a getter should by convention mean an unmodifiable list in our code base.

In the scenario, I would change the service to pass List.copyOf(lines) to the pricing library and have it return a new priced result rather than mutating input, change getDiscounts to return Map.copyOf or an unmodifiable view, and move order lines into an immutable record where the domain allows it.

6Follow-up questions

Is a record with a List component immutable?

Not automatically. A record's fields are final, so the record always points to the same list, but if that list is an ArrayList the caller who passed it in can still add to it, and anyone can modify it through the accessor. The record becomes immutable only when the compact constructor copies the list into an immutable one with List.copyOf, and when the elements themselves are immutable too. A list of mutable objects is shallowly immutable: the list cannot change, but each element can.

Does List.copyOf always copy?

It copies when the argument is a mutable or unknown collection. When the argument is already an unmodifiable list created by List.of or List.copyOf, the JDK is allowed to return the same instance, because copying an immutable list would gain nothing. That is an implementation detail rather than a promise, but it means repeated defensive copies of already immutable lists are cheap.

Why not just return a clone of the ArrayList?

A new ArrayList copy protects our state, but the caller receives a mutable list and may think changing it affects the order, which leads to a different kind of bug. An immutable copy makes the contract explicit: attempts to change it fail loudly with UnsupportedOperationException instead of silently doing nothing useful.

7Conclusion

In this answer, we saw that passing a list or returning a map copies only the reference, so a library or a caller ends up changing the same collection our class owns. We compared List.copyOf, an immutable snapshot, with Collections.unmodifiableList, a read-only view that still reflects our changes, made the value type an immutable record with a defensive copy in its compact constructor, and wrote ownership into the API. Finally, we saw that copying costs time for large collections, which is why immutability by design, copying once at creation, is the better default.

What to say in the interviewAbout 80 seconds aloud

Open with

The root cause is that Java passes references by value. When the service passes its List of order lines to the pricing library, the library gets a copy of the reference to the same ArrayList, so a sort or removeIf in the library reorders and deletes our lines.

Then, if they want more

A getter that returns the internal map has the same problem in reverse: every caller holds a pointer to our state and can clear it. To fix it, I hand out collections that cannot be changed. List.copyOf gives an immutable snapshot, which is what I pass to a library that might keep the list.

Collections.unmodifiableList gives a cheap read-only view, but it still reflects later changes, so I use it for getters where callers only read. Better still, I make value types immutable: a record whose compact constructor does this.lines equals List.copyOf of lines, so it is copied once at creation and the accessor can return it directly.

Where mutation is intended, I document ownership: whether a method modifies its argument and whether it keeps the reference. I also keep the cost in mind: copying a large list on every call is wasteful, which is another reason to design immutable types instead of copying defensively everywhere.

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.
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 service passes its internal List<OrderLine> to a pricing library, and later finds...": https://scrivio-interview-library.netlify.app/java/classes-and-objects/e0701031f3/