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 thefromIndex
(inclusive) to thetoIndex
(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
Parameter | Description |
---|---|
fromIndex | The beginning index (inclusive, must be >= 0 and <= list size) |
toIndex | The ending index (exclusive, must be >= fromIndex and <= list size) |
Return Value
- Returns a view-backed List containing elements from
fromIndex
(inclusive) totoIndex
(exclusive). - The returned list is a “view”—not a deep copy—so modifying it affects the original list.
Exceptions
IndexOutOfBoundsException
: IffromIndex
ortoIndex
are negative, greater than the list size, or iffromIndex > 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
, oradd
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
Aspect | Details |
---|---|
Method Purpose | Create a view-backed subrange of the ArrayList |
Syntax | list.subList(int fromIndex, int toIndex) |
Backed by Original? | Yes, changes reflect in both |
Exceptions | IndexOutOfBoundsException , IllegalArgumentException |
Return Value | List view over the specified range |
Typical Use Cases | Slicing, 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.