SubList Backed View Invalidation
subList hands back a live view: clearing it removes from the backing list, while structural edits to the backing list invalidate the view and throw.
Code
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.List;
public class SliceViews {
public static void main(String[] args) {
List<String> queue = new ArrayList<>(List.of("t1", "t2", "t3", "t4", "t5"));
// subList 返回视图:通过视图 clear 会同步删掉原表中的元素
List<String> window = queue.subList(1, 4);
window.clear();
System.out.println("backing after window.clear: " + queue);
// 重新取空视图并通过视图插入:元素插到窗口起点对应的位置
window = queue.subList(1, 1);
window.add("t-new");
System.out.println("backing after insert: " + queue);
// 反过来直接改原表:旧视图立即失效,再访问就抛 ConcurrentModificationException
window = queue.subList(0, 2);
queue.add("t6");
try {
window.get(0);
} catch (ConcurrentModificationException e) {
System.out.println("stale view rejected: " + e.getClass().getSimpleName());
}
}
}How the snippet works
SubList Backed View Invalidation keeps everything in the class SliceViews and the function main.
Applying it
Running the file prints labeled results such as backing after window.clear:, backing after insert:, stale view rejected: — each operation’s effect is visible in the output.
Statements that matter
List<String> queue = new ArrayList<>(List.of("t1", "t2", "t3", "t4", "t5"));
List<String> window = queue.subList(1, 4);
window = queue.subList(1, 1);
Interactive Tools for This Topic
FAQ
- What does SubList Backed View Invalidation print when run?
- The script runs standalone; its 3 labeled outputs include `backing after window.clear:`, `backing after insert:`, `stale view rejected:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.