Immutability · Topic 4 of 6
Immutable collections
Definition​
List.of, Set.of and Map.of create collections that cannot be changed. List.copyOf makes an independent immutable snapshot, while Collections.unmodifiableList is only a read-only window onto a list that can still change.
Example code​
List.copyOf is a snapshot, unmodifiableList is a live view
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
class Demo {
public static void main(String[] args) {
List<String> source = new ArrayList<>(List.of("a", "b"));
List<String> snapshot = List.copyOf(source); // independent copy
List<String> view = Collections.unmodifiableList(source); // live read-only view
source.add("c");
System.out.println("snapshot: " + snapshot); // unchanged
System.out.println("view: " + view); // shows the change
Map<String, Integer> stock = Map.of("apple", 5, "pear", 2);
try {
stock.put("fig", 1);
} catch (UnsupportedOperationException e) {
System.out.println("Map.of is immutable");
}
}
}
// Output:
// snapshot: [a, b]
// view: [a, b, c]
// Map.of is immutable
Finished this page? Track your progress (saved only in your browser).