Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Java Collections.nCopies: repeated slots can share one mutable object

Last updated: 1 Oct 20264 min read
tutorial
IntermediateBy AITrove Editorial

Collections.nCopies produces an immutable-size list whose positions all refer to the same supplied object.

Distinguish repeated values from independent records

A test fixture that needs three independent mutable notes cannot get them by repeating one StringBuilder. Mutating the object through any slot changes the text visible at every slot. The list rejects replacement operations, but it does not freeze the object itself.

The program prints one reference-identity check and the resulting repeated notes. Shallow copies have the same nested-object hazard even though their node storage is independent.

Choose a factory for independent objects

Construct separate elements in a loop when each slot owns mutable state. For immutable values such as String or a value record, sharing one reference is usually harmless. The contract is about object identity, not the visual similarity of printed values.

Working program

Java
import java.util.*;

public class RepeatedReviewNote {
    public static void main(String[] args) {
        List<StringBuilder> notes = Collections.nCopies(3, new StringBuilder("open"));
        System.out.println(notes.get(0) == notes.get(2));
        notes.get(1).append("-review");
        System.out.println(notes);
    }
}

Output

Output
true
[open-review, open-review, open-review]

Cost and ownership

The list representation can use constant storage for the repeated reference, but creating independent mutable elements would require O(n) objects. A read at an index is constant work; the shared object's mutation cost depends on that object.

Common Mistakes

  • Do not use nCopies for independent mutable records.
  • Do not confuse an unmodifiable list with immutable elements.
  • Do not rely on equal printed values as evidence of separate identities.

Read next

Java LinkedList clone: copied nodes, shared element objects, Java collection factories: rejected updates and shallow element ownership, Java collection views: live wrappers, snapshots and shallow copies, Java LinkedList: operations, internals and failure cases.

java
collections
collections-ncopies-alias
Storage details