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

Java Collections.copy: the destination must already have slots

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

Collections.copy replaces existing destination elements; it does not grow an empty list to fit the source.

Allocate positions before copying

An empty LinkedList has capacity to grow but has no elements to overwrite. Collections.copy requires destination.size() to be at least source.size(). An adapter that expects insertion will fail before producing a backup copy.

The fixture first shows the failure on an empty destination, then creates three placeholder positions and copies the source. A constructor copy such as new ArrayList(source) is simpler when no existing destination must be reused.

Know what was copied

Only element references are copied. A mutable object in the source remains shared with the destination, and extra destination elements remain in place. LinkedList shallow copying shows the same element-ownership boundary.

Working program

Java
import java.util.*;

public class DispatchBackupSlots {
    public static void main(String[] args) {
        List<String> source = Arrays.asList("D-17", "D-23", "D-47");
        LinkedList<String> backup = new LinkedList<String>();
        try { Collections.copy(backup, source); }
        catch (IndexOutOfBoundsException rejected) { System.out.println("slots missing"); }
        backup.addAll(Arrays.asList("reserved", "reserved", "reserved"));
        Collections.copy(backup, source);
        System.out.println(backup);
    }
}

Output

Output
slots missing
[D-17, D-23, D-47]

Cost and ownership

Copying n references takes O(n) time. This implementation allocates destination nodes before the copy and therefore O(n) additional list storage. The operation does not deep-copy mutable records or provide transactional publication.

Common Mistakes

  • Do not expect Collections.copy to append into an empty list.
  • Do not assume a copied reference is an independent mutable object.
  • Do not forget that destination elements beyond source length remain unchanged.

Read next

Java LinkedList clone: copied nodes, shared element objects, Java collection views: live wrappers, snapshots and shallow copies, Java LinkedList: operations, internals and failure cases, Java ArrayList and indexed access.

java
collections
collections-copy-destination-size
Storage details