A collection reference can expose more power than you intend. Returning an internal mutable list lets callers bypass your methods and change your state. Ownership means deciding who may change a container and how other code can inspect it safely.
Work through the example
new ArrayList<>(source) makes a separate container. Adding to that copy does not change source. The copy is shallow: element references are shared. That is safe for immutable strings, but not enough to isolate mutable objects. The task tracker uses immutable Task objects so a shallow snapshot of its list is sufficient.
The word snapshot here means an independent container representing the entries at one point in time. It does not promise deep cloning. A caller can still change their own snapshot; the important contract is that they cannot change the owner's membership through it.
Before Run, write the output and identify the exact line responsible for each result. Each editor is a separate program; names and edits in one box do not carry into the next.
import java.util.List;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
List<String> source = new ArrayList<>();
source.add("Read");
List<String> alias = source;
List<String> snapshot = new ArrayList<>(source);
alias.add("Test");
snapshot.add("Walk");
System.out.println(source);
System.out.println(snapshot);
}
}Check your prediction
[Read, Test]
[Read, Walk]Compare the behavior
An unmodifiable list rejects container edits; it does not freeze objects inside. List.copyOf also rejects null elements. Use that stronger contract when callers need only to read. This example catches the expected UnsupportedOperationException to demonstrate the rule. Do not use exceptions as your normal way of adding items.
import java.util.List;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
List<String> source = new ArrayList<>();
source.add("Read");
List<String> view = List.copyOf(source);
source.add("Test");
System.out.println(view);
try {
view.add("Walk");
} catch (UnsupportedOperationException expected) {
System.out.println("Cannot edit snapshot");
}
}
}Check your prediction
[Read]
Cannot edit snapshotTest both directions of a snapshot
An alias and a copy initially print the same values, so initial equality is not an isolation test. Change the returned container and inspect the owner. Then change the owner and inspect the older returned container. A snapshot should preserve the membership it represented at the time it was taken.
Copying the container does not duplicate each element. Draw two lists with arrows to the same element objects. With immutable strings or validated immutable tasks, those shared arrows are harmless. With a mutable item, changing an item's field remains visible from both containers. Decide whether immutable elements or element copies fit your contract.
An unmodifiable snapshot adds another guarantee: callers cannot add or remove through it. It does not make a shallow copy deep. State which of these promises your method makes—independent membership, no caller edits, immutable elements—rather than describing every returned list simply as safe.
Debug a plausible mistake
Returning a field and returning a copy initially look identical when printed. The distinguishing action is a later change through one reference followed by a read through the other. This is the ownership guarantee the task-tracker repository will need.
Repair the snapshot boundary
Clearing a caller's snapshot must not clear the notebook. After adding Read, taking a snapshot and clearing it, a new notebook snapshot must still have size 1. Predict what the current program actually prints before changing it, then make the smallest repair. The supplied version compiles; its behavior is the problem.
import java.util.List;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
Notebook notebook = new Notebook();
notebook.add("Read");
List<String> snapshot = notebook.snapshot();
snapshot.clear();
System.out.println(notebook.snapshot().size());
}
}
final class Notebook {
private final List<String> titles = new ArrayList<>();
void add(String title) {
titles.add(title);
}
List<String> snapshot() {
return titles;
}
}Hint 1: the idea
A final list field still allows edits to the list object.
Hint 2: a first step
Create a new container inside snapshot rather than returning the owner's reference.
Show one solution
import java.util.List;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
Notebook notebook = new Notebook();
notebook.add("Read");
List<String> snapshot = notebook.snapshot();
snapshot.clear();
System.out.println(notebook.snapshot().size());
}
}
final class Notebook {
private final List<String> titles = new ArrayList<>();
void add(String title) {
titles.add(title);
}
List<String> snapshot() {
return new ArrayList<>(titles);
}
}Expected output after repair:
1The bug was return titles;: the caller received the notebook's own list, so
snapshot.clear() emptied the notebook and the program printed 0. new ArrayList<>(titles) gives the caller a separate list with the same elements;
clearing it leaves the notebook's list alone. final on the field did not help,
because it stops reassigning the field, not changing the list it points to.
Practice independently
Copies & Ownership: practice
The debug above protected a list on its way out of an object. This time
protect one on its way in. Write a Playlist whose constructor receives a
List<String> of titles. It rejects a null list with titles required, and
titles() returns a copy. The caller's later changes to the list it passed in
must not reach the playlist. Main should build a list of Read and Test, make
the playlist, then clear the original list and add Hack to it:
[Read, Test]
[Hack]import java.util.List;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
List<String> input = new ArrayList<>();
input.add("Read");
input.add("Test");
// Make a Playlist from input, then change input and print both.
}
}Hint 1: the idea
After new Playlist(input), the caller still holds a reference to the list it
passed. If the playlist stores that same reference, the caller can still change
the playlist's contents.
Hint 2: a first step
Before changing the class, write the caller's side: build input, create the
playlist, clear input, and print playlist.titles(). When you see the
playlist emptied too, decide what the constructor should store instead of the
caller's reference.
Show one solution
import java.util.List;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
List<String> input = new ArrayList<>();
input.add("Read");
input.add("Test");
Playlist playlist = new Playlist(input);
input.clear();
input.add("Hack");
System.out.println(playlist.titles());
System.out.println(input);
}
}
final class Playlist {
private final List<String> titles;
Playlist(List<String> titles) {
if (titles == null) {
throw new IllegalArgumentException("titles required");
}
this.titles = new ArrayList<>(titles);
}
List<String> titles() {
return new ArrayList<>(this.titles);
}
}Expected output:
[Read, Test]
[Hack]The constructor copies the incoming list, so input.clear() changes only the
caller's list. With this.titles = titles; instead, the playlist would print
[Hack]. titles() copies on the way out for the same reason as the debug
exercise, so ownership is protected at both doors.
Change it and test again
In Playlist, store the incoming list without copying it. Which printed line changes? Restore the copy. Explain why a final list field still permits add and clear. If titles were mutable task objects, what additional design would prevent changes to those objects?
Explain before moving on
Distinguish an alias, a shallow snapshot and an unmodifiable snapshot. Name the guarantees your own accessor should make instead of simply calling it safe.
Completion is saved in this browser only. It does not measure mastery.