liveBook · Manning

List.copyOf

As explained in 100 Java Mistakes and How to Avoid Them

List.copyOf is a Java factory method that creates an unmodifiable list containing the elements of a supplied collection.

List.copyOf(collection) creates an unmodifiable list containing the elements of another collection. Do not confuse it with List.of(), which creates a list from supplied elements, or with addAll(), which adds elements to an existing list. section 8.2

Return a finalized unmodifiable list

List<String> data = new ArrayList<>(); data.addAll(getPredefinedData()); data.addAll(getDataFromPlugins()); data.addAll(getUserSpecificData()); return List.copyOf(data);

Choose the operation that matches the input shape and mutability contract:

  • Use add(object) for one element and addAll(collection) for the elements of another collection. section 8.2
  • Return List.copyOf() when callers should receive an unmodifiable list; do not assume a returned collection is mutable. section 8.5
  • Use toUnmodifiableList() or Stream.toList() for stream-based pipelines when those forms fit the construction. section 8.5

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Defines the factory and contrasts neighboring methods, but does not descend into implementation details.
Examples
Uses comparison tables and a data-assembly example that returns List.copyOf(data).
What it assumes
Assumes familiarity with Java collections, collection method signatures, and the distinction between modifiable and unmodifiable results.
What you can do after
Apply it via Java’s collection factory methods to return an unmodifiable list assembled from another collection.
How it connects
Connects List.copyOf with List.of(), add(), addAll(), Stream.of(), collection.stream(), and unmodifiable collections.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.