Video in progress
Show the difference between Collections.unmodifiableList and List.copyOf with an example.
unmodifiableList is a read-only wrapper over the original list: if the original changes, the wrapper sees the change. List.copyOf creates an independent immutable copy and does not accept null.
📖 Answer
List<String> source = new ArrayList<>(List.of("a", "b"));
List<String> view = Collections.unmodifiableList(source);
List<String> copy = List.copyOf(source);
source.add("c");
System.out.println(view); // [a, b, c] — the change is visible
System.out.println(copy); // [a, b]
In both, add/set/remove throw an UnsupportedOperationException. The difference is the link to the original source.
This matters when a class returns its internal state to the outside:
public List<Item> items() {
return Collections.unmodifiableList(items); // the caller can't modify it, but sees later changes
}
When you store a list that came in from outside in a constructor, List.copyOf is the better choice. Otherwise the caller changes their own list and breaks your object.
A small bonus: if the argument is already an immutable List.of list, List.copyOf returns that same object without copying.
Sign up to mark studied questions and save your progress.