Video in progress

Strong Junior 🧺 Collections

What happens to the original list if you modify a list returned by subList?

subList is not a copy but a view of a slice of the original list. What you write to it shows up in the original. And if the original is modified other than through the subList, every later access throws a ConcurrentModificationException.

📖 Answer

List<Integer> all = new ArrayList<>(List.of(1, 2, 3, 4, 5, 6));
List<Integer> mid = all.subList(1, 4);   // [2, 3, 4]

mid.set(0, 20);      // all = [1, 20, 3, 4, 5, 6]
mid.clear();         // all = [1, 5, 6]: a handy way to delete a range

List<Integer> part = all.subList(0, 2);
all.add(7);
part.size();         // ConcurrentModificationException

all.subList(from, to).clear() is the shortest way to delete a range, so keep it in mind.

Another hidden problem: if you take a small subList of a big list and keep it in a cache or a field, the whole big list is kept from the GC too. If you need an independent slice, use new ArrayList<>(all.subList(a, b)) or List.copyOf(...).