Collections: Collections.copy requires the destination to be pre-sized

Collections.copy overwrites the front of the destination list in place; the destination must already have at least as many elements as the source or it throws IndexOutOfBoundsException instead of growing.

Code
List<String> source = List.of("x", "y", "z");
List<String> dest = new ArrayList<>(List.of("1", "2", "3", "4"));
Collections.copy(dest, source);
System.out.println("After copy (extra tail kept): " + dest);
List<String> tooSmall = new ArrayList<>(List.of("1"));
try {
    Collections.copy(tooSmall, source);
} catch (IndexOutOfBoundsException e) {
    System.out.println("Undersized destination throws: " + e.getClass().getSimpleName());
}
Output
After copy (extra tail kept): [x, y, z, 4]
Undersized destination throws: IndexOutOfBoundsException
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms