LinkedList.addAll(index, source) inserts the source elements at a position; an aliased source makes the input change while the insertion runs.
Java LinkedList addAll: snapshot an aliased source
Name the source boundary
A source can be the destination itself or a live subList view backed by it. The List contract does not define the result when the source changes during addAll. A result observed on one JDK build is therefore a poor application rule. Take a snapshot before touching the destination, then insert that fixed sequence.
The program copies two selected dispatch IDs before adding them after the first item. That copy also prevents a later edit to the original list from changing which IDs the operation intended to duplicate. A subList is a view, so passing it directly would keep the alias in place.
Charge the real cost
Copying k references needs O(k) extra space. Finding the insertion point in a LinkedList costs O(min(index, n-index)) traversal; linking the k new nodes costs O(k). If the caller already owns a ListIterator at the insertion point, cursor-local edits can avoid another search, but the input still needs a stable ownership rule.
The snapshot is shallow. If each element is mutable, another thread can still alter an element after the snapshot. The list controls sequence membership, not the state of each referenced object.
Working program
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
public class DispatchReplayInsertion {
public static void main(String[] args) {
LinkedList<String> pendingDispatches = new LinkedList<>(
Arrays.asList("load-47", "seal-82", "handoff-15"));
List<String> replay = new ArrayList<>(pendingDispatches.subList(0, 2));
pendingDispatches.addAll(1, replay);
System.out.println(pendingDispatches);
}
}Output
[load-47, load-47, seal-82, seal-82, handoff-15]Cost and ownership
A defensive list snapshot costs O(k) references, followed by O(n + k) traversal and insertion in the worst case. The operation is not an atomic update visible to unsynchronized readers; see the separate locking contract before sharing the list across threads.
Common Mistakes
- Do not pass the destination or its live subList as the addAll source.
- Do not call a shallow snapshot a deep copy of mutable elements.
- Do not assume an indexed LinkedList insertion has array-style O(1) positioning.
Read next
Java LinkedList: operations, internals and failure cases, Java LinkedList subList: a live window, not a snapshot, Java LinkedList ListIterator: edit at a cursor without repeated searches, Java synchronizedList iteration: hold the wrapper lock.
