LinkedList.subList returns a backed view whose permitted edits change the original list.
Java LinkedList subList: a live window, not a snapshot
The Java 8 program below compiles without external libraries; its output is checked against a real run.
Treat the window as shared state
A billing batch keeps four receipt identifiers and exposes only its middle two to a correction step. Setting one value through the window updates the original list. Clearing the window removes those two nodes from the backing list; the end elements remain.
The method returns a view, not a detached copy. If a caller needs a stable membership snapshot, construct a new list from the window and decide separately whether its element objects must be copied. View ownership covers that second question.
Keep structural changes inside the view
The List contract says the view's semantics become undefined if the backing list is structurally changed outside the view. A particular JVM may throw a ConcurrentModificationException after that mistake, but code should not depend on the exception. Instead, keep one owner for structural edits or rebuild the window after the parent changes.
Working program
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
public class ReceiptCorrectionWindow {
public static void main(String[] args) {
LinkedList<String> receipts = new LinkedList<>(Arrays.asList("R-11", "R-12", "R-13", "R-14"));
List<String> window = receipts.subList(1, 3);
window.set(0, "R-12-rechecked");
System.out.println(receipts);
window.clear();
System.out.println(receipts);
}
}Output
[R-11, R-12-rechecked, R-13, R-14]
[R-11, R-14]Costs and boundaries
Obtaining a subList is a view operation; locating and changing a linked-list position may traverse nodes. Clearing k elements still changes the backing structure. The view retains a reference to that structure rather than allocating k independent elements.
Common Mistakes
- Do not call a backed view an immutable snapshot.
- Do not structurally mutate the parent while continuing to use an old view.
- Do not assume copying list membership deep-copies mutable elements.
Read next
Java LinkedList: operations, internals and failure cases, Java collection views: live wrappers, snapshots and shallow copies, Java LinkedList clone: copied nodes, shared element objects.
