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

Java Collections.rotate on a subList: change only a live window

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

Collections.rotate changes element order within the supplied List, and a subList argument writes through to its parent list.

Bound the reordering region

A dispatch schedule may allow a three-slot shift while keeping the opening and closing duties fixed. Passing schedule.subList(1, 4) rotates only the middle window. The parent list changes because the subList is a view, not a detached copy.

The fixture moves the last middle duty to the start of that window. Sublist ownership explains why callers holding the parent see the update. Do not mutate the parent structurally while relying on a retained sublist view.

Do not confuse rotation with moving nodes

The API promises the resulting order, not a particular node-relinking algorithm. On a linked list, the implementation may exchange element references or use a temporary array. Choose the operation because its semantics fit, not because you expect a specific internal shortcut.

Working program

Java
import java.util.*;

public class DutyWindowRotation {
    public static void main(String[] args) {
        LinkedList<String> duties = new LinkedList<String>(Arrays.asList("open", "scan", "pack", "seal", "close"));
        Collections.rotate(duties.subList(1, 4), 1);
        System.out.println(duties);
    }
}

Output

Output
[open, seal, scan, pack, close]

Cost and ownership

Rotation of a window of k elements costs at least O(k) element visits and may use implementation-specific temporary storage. The subList itself is a view; it does not allocate a second independent schedule.

Common Mistakes

  • Do not expect subList to isolate the parent from mutations.
  • Do not assume rotation physically relinks LinkedList nodes.
  • Do not keep a subList across unrelated structural edits to its parent.

Read next

Java LinkedList subList: a live window, not a snapshot, Java LinkedList: operations, internals and failure cases, Collections.unmodifiableList is a live view, not a snapshot, Java sorting: comparators, stability, and ownership.

java
collections
collections-rotate-sublist
Storage details