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
