Java Utility Library

Java ArrayList - subList() Method



The java.util.ArrayList.subList() method returns a view of the portion of this List between fromIndex, inclusive, and toIndex, exclusive. (If fromIndex and toIndex are equal, the returned List is empty.) The returned List is backed by this List, so changes in the returned List are reflected in this List, and vice-versa. The returned List supports all of the optional List operations supported by this List.

Syntax

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

Here, E is the type of element maintained by the container.


Parameters

fromIndex Specify the low endpoint (inclusive) of the subList.
toIndex Specify the high endpoint (exclusive) of the subList.

Return Value

Returns a view of the specified range within this List.

Exception

  • Throws IndexOutOfBoundsException, if an endpoint index value is out of range (fromIndex < 0 || toIndex > size)
  • Throws IllegalArgumentException, if the endpoint indices are out of order (fromIndex > toIndex)

Example:

In the example below, the java.util.ArrayList.subList() method returns a view of the portion of the given list.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating an ArrayList
    ArrayList<Integer> ArrList = new ArrayList<Integer>();

    //populating the ArrayList
    ArrList.add(10);
    ArrList.add(20);
    ArrList.add(30);
    ArrList.add(40);
    ArrList.add(50);
    ArrList.add(60);
    ArrList.add(70);  
     
    //printing the ArrayList
    System.out.println("ArrList contains: "+ ArrList);    

    //creating a portion view of the ArrayList
    List sublist = ArrList.subList(2, 5);

    //printing sublist
    System.out.println("sublist contains: "+ sublist);  
  }
}

The output of the above code will be:

ArrList contains: [10, 20, 30, 40, 50, 60, 70]
sublist contains: [30, 40, 50]

❮ Java.util - ArrayList