List.of Unmodifiable Snapshot Versus View
List.of builds unmodifiable snapshots that reject null elements and mutation, while Arrays.asList stays a fixed-size view and List.copyOf a real copy.
Code
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ListShapes {
public static void main(String[] args) {
// List.of is a true unmodifiable snapshot: structural edits always throw
List<String> snapshot = List.of("orders", "billing");
try {
snapshot.add("auth");
} catch (UnsupportedOperationException e) {
System.out.println("add rejected");
}
// null elements are rejected at construction, not discovered later on read
try {
List.of("orders", null);
} catch (NullPointerException e) {
System.out.println("null rejected");
}
// by contrast, Arrays.asList is a fixed-size view: set is allowed and writes through
List<String> view = Arrays.asList("orders", "billing");
view.set(0, "auth");
System.out.println("view: " + view);
// List.copyOf snapshots a mutable list; the two diverge from then on
List<String> mutable = new ArrayList<>(List.of("orders", "billing"));
List<String> frozen = List.copyOf(mutable);
mutable.add("auth");
System.out.println("frozen: " + frozen);
}
}What the demo contrasts
List.of builds a snapshot: add throws UnsupportedOperationException and the printed line reads add rejected. Construction is equally strict: List.of(“orders”, null) raises NullPointerException on the spot, catching bad data at the entry point.
Arrays.asList behaves differently: set is allowed and writes through to the array, which is why the view prints auth after one set call. List.copyOf then freezes a real copy of a mutable list; the source keeps accepting add afterwards and the frozen list stays two elements.
Caveats and details
- Fixed-size view: the size never changes, the values can.
- copyOf never wraps; it always copies, so later source edits stay invisible.
Interactive Tools for This Topic
FAQ
- When is Arrays.asList acceptable?
- When a fixed-size view is intended and callers only replace elements through set; any structural change still throws, exactly as the view demo shows.
Report a problem with this exampleOpens a pre-filled issue on GitHub.