Java’s List.copyOf(), Set.copyOf(), and Map.copyOf() create unmodifiable collection copies and reject null elements. Applying copyOf at method boundaries validates input without requiring repeated manual traversal. section 5.1.1
Validate once at the boundary
public void process(Collection<String> data) { data = List.copyOf(data); … } If the argument is already a suitable copyOf result, the method can reuse it instead of creating another copy. Repeating this boundary pattern across methods therefore performs at most one copy and null check. section 5.1.1
Use copyOf when:
- You need an unmodifiable collection and want null elements rejected immediately. section 5.1.1
- You are passing the same collection through several methods and want to avoid repeated full traversal. section 5.1.1
