Skip to content

WebDevHubs

  • Home
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • Java
  • Selenium
  • PHP
  • Python
  • Programs
  • Toggle search form

Java ArrayList subList() Method

Posted on July 24, 2025July 24, 2025 By Admin No Comments on Java ArrayList subList() Method

The subList() method is a powerful feature of the Java ArrayList class. It allows you to extract a portion of a list as a separate, view-backed list, based on a specified range of indices. This provides an efficient way to work with slices of data without creating unnecessary copies, making your code neater and more performance-oriented.

What Is the subList() Method in ArrayList?

  • The subList() method creates a view of a portion of the original list—from the fromIndex (inclusive) to the toIndex (exclusive).
  • The new list is not a separate copy; changes to the sublist are reflected in the original list and vice versa.
  • It is especially useful when you need to operate on a segment of a list (batch processing, windowing, or partitioning tasks).

Syntax

public List<E> subList(int fromIndex, int toIndex)

Where:

  • fromIndex (inclusive): Starting index of the sublist.
  • toIndex (exclusive): Ending index (element at this position is not included).
  • E is the type of elements in the list.

Parameters

ParameterDescription
fromIndexThe beginning index (inclusive, must be >= 0 and <= list size)
toIndexThe ending index (exclusive, must be >= fromIndex and <= list size)

Return Value

  • Returns a view-backed List containing elements from fromIndex (inclusive) to toIndex (exclusive).
  • The returned list is a “view”—not a deep copy—so modifying it affects the original list.

Exceptions

  • IndexOutOfBoundsException: If fromIndex or toIndex are negative, greater than the list size, or if fromIndex > toIndex.
  • IllegalArgumentException: If the indices do not define a valid range (e.g., fromIndex > toIndex).

How Does subList() Work Internally?

  • The method returns a “window” into the original list, with indices shifted according to the specified range.
  • Backed by original: Mutations such as set, remove, or add in the sublist reflect in the original list, and vice versa (but use caution—structural changes outside the sublist often invalidate the view).
  • Use the resulting sublist like any other list: iterate, update, or further process as needed.

Examples of the subList() Method

1. Extracting a Sublist by Range

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

public class Main {
    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<>();
        names.add("Alice");
        names.add("Bob");
        names.add("Charlie");
        names.add("David");
        names.add("Eva");

        // Extract sublist from index 1 to 4 (Bob, Charlie, David)
        List<String> subset = names.subList(1, 4);

        System.out.println(subset); // Output: [Bob, Charlie, David]
    }
}

2. Modifying a Sublist Affects the Original List

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

public class Demo {
    public static void main(String[] args) {
        ArrayList<Integer> numbers = new ArrayList<>();
        numbers.add(10);
        numbers.add(20);
        numbers.add(30);
        numbers.add(40);
        numbers.add(50);

        List<Integer> part = numbers.subList(2, 5);
        part.set(0, 300); // Alters numbers at index 2

        System.out.println(numbers); // Output: [10, 20, 300, 40, 50]
    }
}

3. Removing Elements from a Sublist

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

public class RemoveExample {
    public static void main(String[] args) {
        ArrayList<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");
        fruits.add("Date");

        List<String> window = fruits.subList(1, 3); // Banana, Cherry
        window.clear();

        System.out.println(fruits); // Output: [Apple, Date]
    }
}

4. Invalid Index Example (Throws Exception)

import java.util.ArrayList;

public class InvalidSublist {
    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<>();
        list.add(1); list.add(2); list.add(3);

        try {
            List<Integer> broken = list.subList(2, 5); // toIndex > size
        } catch (IndexOutOfBoundsException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

Output:

Error: toIndex = 5

Important Notes

  • The sublist is a view, not a copy—mutate with care!
  • Structural modifications to the parent list outside the sublist—in ways other than via the sublist—will usually cause the sublist to become invalid and throw a ConcurrentModificationException on future use.
  • If you need an independent list, simply wrap the sublist with a new ArrayList<>(...).
  • The sublist supports all standard list operations: get, set, add, remove, clear, etc.

Summary

AspectDetails
Method PurposeCreate a view-backed subrange of the ArrayList
Syntaxlist.subList(int fromIndex, int toIndex)
Backed by Original?Yes, changes reflect in both
ExceptionsIndexOutOfBoundsException, IllegalArgumentException
Return ValueList view over the specified range
Typical Use CasesSlicing, batch processing, partitioning

Typical Use Cases

  • Batch processing: Operate on a chunk or window of list data.
  • Partitioning: Divide a list into sublists for paging or tasks.
  • Bulk updates/removals: Remove, edit, or analyze a range of elements at once.
  • Efficient filtering: Work efficiently without creating unnecessary deep copies.
Java Tags:Java-ArrayList, Java-ArrayList-Method, Java-Collections

Post navigation

Previous Post: Java ArrayList spliterator() Method
Next Post: Java ArrayList toArray() Method

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Java ArrayList
  • Java ArrayList Methods
  • Java ArrayList add() Method
  • Java ArrayList addAll() Method
  • Java ArrayList clear() Method
  • Java ArrayList clone() Method
  • Java ArrayList contains() Method
  • Java ArrayList ensureCapacity() Method
  • Java ArrayList forEach() Method
  • Java ArrayList get() Method
  • Java ArrayList indexOf() Method
  • Java ArrayList isEmpty() Method
  • Java ArrayList iterator() Method
  • Java ArrayList lastIndexOf() Method
  • Java ArrayList listIterator() Method
  • Java ArrayList remove() Method
  • Java ArrayList removeAll() Method
  • Java ArrayList removeIf() Method
  • Java ArrayList replaceAll() Method
  • Java ArrayList retainAll() Method
  • Java ArrayList set() Method
  • Java ArrayList size() Method
  • Java ArrayList sort() Method
  • Java ArrayList spliterator() Method
  • Java ArrayList subList() Method
  • Java ArrayList toArray() Method
  • Java ArrayList trimToSize() Method

Recent Posts

  • Java ArrayList trimToSize() Method
  • Java ArrayList toArray() Method
  • Java ArrayList subList() Method
  • Java ArrayList spliterator() Method
  • Java ArrayList sort() Method

Recent Comments

No comments to show.

Important Pages

  • About Us
  • Contact Us
  • Terms of Use
  • Privacy Policy

Web Development

  • HTML
  • CSS
  • JavaScript
  • PHP

Programming Languages

  • Java
  • Python
  • PHP
  • Programs

Others

  • Selenium
  • Lodash
  • Java ArrayList
  • JavaScript Array Methods

Copyright © 2025 WebDevHubs.

Powered by PressBook Green WordPress theme