liveBook · Manning

copyOf method

As explained in 100 Java Mistakes and How to Avoid Them

A Java collection copyOf method creates an unmodifiable collection copy that rejects null elements and may return an existing suitable immutable copy.

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

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains null rejection, unmodifiable results, traversal cost, and reuse of suitable immutable copies.
Examples
Shows process(Collection<String>) assigning List.copyOf(data) at method entry.
What it assumes
Assumes Java collection knowledge while teaching boundary validation and the distinction between null elements and null collections.
What you can do after
Apply List.copyOf, Set.copyOf, or Map.copyOf to enforce unmodifiable, null-free collection inputs.
How it connects
Connects defensive copying with null values, unmodifiable collections, and empty-container conventions.

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.