In Java, subList(fromIndex, toIndex) returns a List holding the elements from index fromIndex (included) up to toIndex (excluded) of an ArrayList.
The result is a view, not a copy: it shares storage with the original list. Setting, sorting, or clearing through the view changes the original. To get an independent list, wrap it: new ArrayList<>(list.subList(a, b)).
An instance method of java.util.ArrayList (Java 1.2+): a resizable-array list with index access that allows null and duplicates and is not thread-safe.
Syntax
The start index is included, the end index is not.
Java
List<String> list = new ArrayList<>(Arrays.asList("a", "b", "c", "d"));
List<String> mid = list.subList(1, 3); // [b, c] (a view)
List<String> copy = new ArrayList<>(mid); // independent copy
list.subList(0, 2).clear(); // list is now [c, d]
Call
What it does
list.subList(a, b)
A view of indexes a to b - 1.
new ArrayList<>(list.subList(a, b))
An independent copy of that range.
list.subList(a, b).clear()
Removes a range of elements from the list.
list.subList(a, b).sort(c)
Sorts only that part of the list.
The view has toIndex - fromIndex elements, and its own indexes start at 0. subList(i, i) is a valid empty view.
Library declarations
Java
// java.util.ArrayList<E>
public List<E> subList(int fromIndex, int toIndex)
// Declared in List<E>
Parameters
Parameter
Description
fromIndex (int)
First index of the range (inclusive).
toIndex (int)
End of the range (exclusive). Must not be greater than size().
old view: ConcurrentModificationException
fresh view: [a, b]
subList(3, 1): IllegalArgumentException
How It Works
View first.firstTwo is created while letters has four elements.
Direct change.letters.add("e") changes the size of the original list without going through the view.
Stale view. The next use of firstTwo, even just size(), detects the change and throws ConcurrentModificationException. Creating a fresh view works fine.
Reversed indexes. A start index greater than the end index is an IllegalArgumentException, not an index-range error.
Frequently Asked Questions
No. It returns a view backed by the original list. Wrap it in new ArrayList<>(...) for an independent copy.
No. fromIndex is included and toIndex is excluded, so subList(1, 3) holds indexes 1 and 2.
Call list.subList(from, to).clear().
The original list was structurally changed after the view was created. Create a new view after the change.
It throws IllegalArgumentException because the start index is greater than the end index.