Java Reference ยท Collections
Java List.subList() method
Reference for Java List.subList(): get a live view of a range, clear or sort part of a list, copy to an independent list and avoid the stale-view exception.
subList(fromIndex, toIndex) returns the portion of a list between fromIndex (inclusive) and toIndex (exclusive). The result is a view, not a copy: reading it reads the parent, and writing to it writes to the parent. This is useful for range operations such as list.subList(2, 5).clear(), which removes exactly that range.
Because the view stays linked to the parent, changing the parent's size directly (by add or remove on the parent) makes the view stale, and the next use throws ConcurrentModificationException. Copy it into a new list when you need an independent snapshot.
List<Integer> firstThree = numbers.subList(0, 3); numbers.subList(2, 5).clear();
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
List<E> subList(int fromIndex, int toIndex)
| Name | Description |
|---|---|
fromIndex |
Start index, inclusive. |
toIndex |
End index, exclusive. fromIndex == toIndex gives an empty view. |
Returns: a List view of the range. For lists created by List.of() the result is immutable too.
Throws: IndexOutOfBoundsException if fromIndex < 0 or toIndex > size(); IllegalArgumentException if fromIndex > toIndex.
Usage notes
- View semantics: non-structural changes (
set,sort,replaceAll) are visible on both sides; structural changes through the view update the parent. - Stale views: after a structural change made directly on the parent, using the view throws
ConcurrentModificationException. - Range operations:
subList(a, b).clear()removes a range in one shift;Collections.reverse(),sort()andCollections.max()work on a range the same way. - Copy for safety:
new ArrayList<>(list.subList(a, b))orList.copyOf(...). Do this before storing the result in a field. - Memory: a long-lived view keeps the whole parent list in memory.
- Not for arrays:
Arrays.copyOfRange()copies array ranges;Arrays.asList(array).subList(...)is a view of an array wrapper. - Nested views are allowed and share the same parent.
- Java 21:
reversed()is an alternative view when you want the whole list backwards.