Java ArrayList.subList(): Extracting Range Views & Slicing Lists

The ArrayList.subList(int fromIndex, int toIndex) method returns a live List<E> view of the portion of the list between fromIndex (inclusive) and toIndex (exclusive) in O(1) constant time without copying the underlying array.

Backed View Behavior: Because the returned List<E> is backed directly by the original ArrayList, calling set(), add(), or clear() on the subList modifies the parent list in place (delegating slice deletion to removeRange()).

1. Syntax, Method Signature & Half-Open Range Rule 🔝

Declared in java.util.ArrayList<E> (implementing List.subList):

 // Returns a view of the portion of this list between fromIndex (inclusive) and toIndex (exclusive)
public List<E> subList(int fromIndex, int toIndex)
Element Type / Rule Operational Description
fromIndex int (Inclusive) Low endpoint (0-based starting index) of the subList.
toIndex int (Exclusive) High endpoint (index immediately after the last included element).
Return Value List<E> (O(1)) Backed view of length toIndex - fromIndex (empty if fromIndex == toIndex).

2. Basic Range Extraction & Empty Slice 🔝

Calling languages.subList(1, 4) returns a view of indices 1, 2, and 3 (4 - 1 = 3 elements). When fromIndex == toIndex (such as subList(1, 1)), the returned view is empty ([]):

ArrayList<String> languages = new ArrayList<>(
    Arrays.asList("Java", "PHP", "HTML", "Python", "PhotoShop", "C++")
);
System.out.println("Full list:     " + languages);

List<String> slice = languages.subList(1, 4);  // Indices 1, 2, 3 (4 is exclusive)
System.out.println("subList(1, 4): " + slice);
System.out.println("subList(1, 1): " + languages.subList(1, 1));  // []

Terminal Output:

Full list:     [Java, PHP, HTML, Python, PhotoShop, C++]
subList(1, 4): [PHP, HTML, Python]
subList(1, 1): []

3. Live Backed View: Mutations Write Through to the Parent List 🔝

Unlike Python list slicing (which creates a new list copy), ArrayList.subList() returns a window over the parent list's array. Calling view.set(0, ...) or view.clear() mutates mainList directly:

ArrayList<String> mainList = new ArrayList<>(Arrays.asList("A", "B", "C", "D"));
List<String> view = mainList.subList(1, 3);  // Views ["B", "C"]

view.set(0, "B-Updated");  // Modifies index 1 of mainList!
System.out.println("Parent after view.set(0): " + mainList);

view.clear();  // Deletes ["B-Updated", "C"] directly from mainList!
System.out.println("Parent after view.clear:  " + mainList);

Terminal Output:

Parent after view.set(0): [A, B-Updated, C, D]
Parent after view.clear:  [A, D]

4. Creating an Independent ArrayList Copy from a subList() 🔝

If you want a standalone ArrayList copy that you can modify without affecting the original list, pass the subList() view to the ArrayList copy constructor new ArrayList<>(source.subList(1, 3)):

ArrayList<String> src = new ArrayList<>(Arrays.asList("Java", "PHP", "HTML"));
ArrayList<String> copy = new ArrayList<>(src.subList(1, 3));
copy.add("Rust");
System.out.println("Copy: " + copy + " | Source: " + src);

Terminal Output:

Copy: [PHP, HTML, Rust] | Source: [Java, PHP, HTML]

5. Exception Rules: IllegalArgumentException vs IndexOutOfBoundsException 🔝

ArrayList.subList() enforces two distinct boundary checks:

  • IllegalArgumentException: Thrown if the endpoints are reversed (fromIndex > toIndex, such as subList(2, 1)).
  • IndexOutOfBoundsException: Thrown if fromIndex < 0 or toIndex > size() (such as subList(1, 10)).
ArrayList<String> languages = new ArrayList<>(Arrays.asList("Java", "PHP", "HTML"));

try {
    languages.subList(2, 1);  // fromIndex (2) > toIndex (1) -> IllegalArgumentException!
} catch (IllegalArgumentException ex) {
    System.out.println("Caught (2, 1): " + ex.getMessage());
}
try {
    languages.subList(1, 10);  // toIndex (10) > size (3) -> IndexOutOfBoundsException!
} catch (IndexOutOfBoundsException ex) {
    System.out.println("Caught (1, 10): " + ex.getMessage());
}

Terminal Output:

Caught (2, 1): fromIndex(2) > toIndex(1)
Caught (1, 10): toIndex = 10

6. Comparison: Live View vs Detached Copy vs Range Delete 🔝

Choosing the right subList() pattern for your goal:

Idiom Complexity Behavior & Use Case
List<E> v = list.subList(a, b) O(1) Zero-copy live view; edits write through to list.
new ArrayList<>(list.subList(a, b)) O(b - a) Allocates an independent, detached ArrayList<E> copy.
list.subList(a, b).clear() O(n) Deletes indices a..b-1 from list in 1 array shift.

7. Production Recipe: Sorting Only a Sub-Range of an ArrayList 🔝

Passing nums.subList(1, 5) to Collections.sort() sorts only indices 1..4 in place while leaving index 0 and index 5 untouched:

public class PartialSliceSort {
    public static void main(String[] args) {
        ArrayList<Integer> nums = new ArrayList<>(Arrays.asList(99, 40, 10, 30, 20, 88));
        Collections.sort(nums.subList(1, 5));
        System.out.println("Middle sorted: " + nums);
    }
}

Terminal Output:

Middle sorted: [99, 10, 20, 30, 40, 88]

8. Practical Recipe: Clamped Top-N Slice Helper 🔝

Using Math.min(n, list.size()) as toIndex safely returns up to n elements without throwing an IndexOutOfBoundsException when the list has fewer than n items:

ArrayList<String> items = new ArrayList<>(Arrays.asList("Gold", "Silver"));
List<String> top5 = items.subList(0, Math.min(5, items.size()));
System.out.println("Top 5 of 2-item list: " + top5);

Terminal Output:

Top 5 of 2-item list: [Gold, Silver]

9. Common Developer Pitfalls & Traps 🔝

ClassCastException: Casting (ArrayList<E>) list.subList(a, b)

list.subList(a, b) returns an instance of the private inner class ArrayList.SubList (which extends AbstractList, not ArrayList). Writing ArrayList<String> s = (ArrayList<String>) list.subList(1, 3); crashes at runtime with a ClassCastException! Declare the variable as List<String> or wrap it in new ArrayList<>(list.subList(1, 3)).

Mutating the Parent List Invalidates Existing subList Views

If you create List<String> sub = list.subList(0, 2); and then call list.add("New") directly on the parent list, any subsequent call to sub.get(0) or sub.size() throws a ConcurrentModificationException.

10. Complete Compilable Java Program 🔝

Compile and run this verification class in any Java environment:

public class ArrayListSubListFullDemo {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>(Arrays.asList("A", "B", "C", "D"));
        List<String> sub = list.subList(1, 3);
        if (sub.size() == 2 && sub.get(0).equals("B")) {
            System.out.println("Check 1 Passed: subList(1, 3) has size 2 and starts at 'B'.");
        }
        sub.set(1, "C-Mod");
        if (list.get(2).equals("C-Mod")) {
            System.out.println("Check 2 Passed: Write-through to parent index 2 verified.");
        }
        System.out.println("All ArrayList.subList() verification checks passed!");
    }
}

Terminal Output:

Check 1 Passed: subList(1, 3) has size 2 and starts at 'B'.
Check 2 Passed: Write-through to parent index 2 verified.
All ArrayList.subList() verification checks passed!

11. Frequently Asked Questions (FAQ) 🔝

Does holding a small subList() of a huge ArrayList cause a memory leak?

Yes! Because a subList view holds a direct reference to the parent ArrayList, keeping a 2-element subList alive prevents the entire 1,000,000-element parent ArrayList from being garbage-collected. Copy it via new ArrayList<>(hugeList.subList(0, 2)) if the parent list is no longer needed.

How does indexing work inside a subList()?

Indices inside subList(fromIndex, toIndex) are relative to the slice: sub.get(0) reads parent.get(fromIndex).

Can I call subList() on another subList()?

Yes. Chaining list.subList(1, 5).subList(1, 3) creates a nested view backed by the original array.

Is subList() serializable?

No! ArrayList.SubList does not implement java.io.Serializable. Always wrap a slice in new ArrayList<>(sub) before serializing it over the network or to disk.

Further Reading & Related Tutorials 🔝


Java



plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer