Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

List.subList — a view of a list range

`List.subList` returns a view backed by the original list, not a copy. The start index is included and the end index is excluded.

Version: Java SE 21

Syntax

List<E> subList(int fromIndex, int toIndex)
list.subList(fromIndex, toIndex)
Valid bounds: 0 <= fromIndex <= toIndex <= list.size()

List.subList(fromIndex, toIndex) is an instance method of java.util.List<E>. It takes two zero-based int indices and returns a List<E> for the half-open range [fromIndex, toIndex). list.subList(2, 5) covers indices 2, 3 and 4; list.subList(0, 4) returns a view of the first four elements of the original list, provided that list contains at least four elements. The view has its own zero-based indices.

Valid bounds satisfy 0 <= fromIndex <= toIndex <= list.size(). Equal valid bounds give an empty view, including at the end of the list. The List contract lists IndexOutOfBoundsException for invalid bounds; ArrayList separately documents IllegalArgumentException for fromIndex > toIndex when the endpoints are within bounds.

The view remains backed by the original list. Non-structural changes in the selected range, such as replacing an element with set when supported, are visible in both directions. The view supports the same optional operations as the original list. If clear is supported, list.subList(fromIndex, toIndex).clear() removes that range from the original list.

If the original list is structurally modified other than through the returned view, the contract no longer defines the view's behavior. This includes size changes and other changes that can disrupt an iteration in progress, even outside the selected range. Do not rely on a ConcurrentModificationException. If you need an independent, mutable list, make new ArrayList<>(view) beforehand. It is a shallow copy: the elements themselves are not copied.

Examples

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>(List.of("A", "B", "C", "D", "E", "F"));
        List<String> view = list.subList(2, 5);
        System.out.println(view);

        view.set(0, "X");
        list.set(3, "Y");
        System.out.println(list);
        System.out.println(view);

        List<String> copy = new ArrayList<>(view);
        view.clear();
        System.out.println(list);
        System.out.println(copy);
    }
}

Result

[C, D, E]
[A, B, X, Y, E, F]
[X, Y, E]
[A, B, F]
[X, Y, E]

The view starts at `C`, so `view.set(0, "X")` replaces the element at index 2 of the original list. Then `list.set(3, "Y")` is visible in the view. After `view.clear()`, the original list contains `[A, B, F]`, but the copy keeps `[X, Y, E]`.

Related lessons

  • Java · Lesson 21 · Advanced · Version: 2
  • Java · Lesson 57 · Intermediate · Version: 2

Sources