Video in progress
What is the difference between `Collections.unmodifiableList(list)` and `List.copyOf(list)`, and which pattern is it related to?
unmodifiableList is a read-only proxy (view) wrapped around the original list: you can't modify it, but if the owner of the original list changes it, the change is visible. List.copyOf creates an independent, immutable copy and doesn't accept null elements.
📖 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] — it changed!
System.out.println(copy); // [a, b]
view.add("d"); // UnsupportedOperationException
unmodifiableList wraps the original list and blocks the mutating methods (add, set, remove) with an exception, while passing read methods straight through. This is a protection proxy, or a restricting decorator: no data is copied, so it is O(1) and cheap.
Where this difference bites: a class returns its internal list from a getter wrapped in unmodifiableList, and outside code keeps it thinking it's a "snapshot". Later the class changes the list, and the outside code unexpectedly sees new elements. If it iterates on another thread, you can also get a ConcurrentModificationException.
Which one to use when:
- to store a collection passed into a constructor, use
List.copyOf(so outside code can't change it afterwards); - to hand out a large internal list for frequent reads, when seeing changes is fine, use
unmodifiableList.
One more subtle point: List.copyOf throws a NullPointerException if it sees a null element; and if the argument is already an immutable list, it may return that same list without copying. stream().toList() from Java 16 also gives an immutable list, but it allows null.
Sign up to mark studied questions and save your progress.