What is ArrayList.subList in Java?

The ArrayList.subList method returns a view/portion of the original list between fromIndex (included) and toIndex (not included).

Syntax

arrayListObj.subList(int fromIndex, int toIndex);
  • fromIndex: Index from which the sublist starts. If fromIndex is less than 0, then IndexOutOfBoundsException will be thrown. If the fromIndex is greater than toIndex, then IllegalArgumentException will be thrown.

  • toIndex: Index at which the sublist ends. The element at the endIndex will not be considered. If toIndex is greater than ArrayList size then, IndexOutOfBoundsException will be thrown.

  • The subList method returns a portion of the ArrayList object as a List object.

List returned for arrayListObj.subList(0,4)
import java.util.ArrayList;
import java.util.List;
class GetSubList {
public static void main(String[] args) {
ArrayList<String> strList = new ArrayList<>();
strList.add("E");
strList.add("D");
strList.add("U");
strList.add("C");
strList.add("T");
strList.add("I");
strList.add("V");
strList.add("E");
System.out.println("The list is " + strList);
List<String> strListCopy = strList.subList(0, strList.size()); // returns complete list
System.out.println("\nGetting complete list by calling strList.sublist(0, strList.size()) \n" + strListCopy);
List<String> firstThreeStr = strList.subList(0, 3);
System.out.println("\nGetting first 3 letters of the list by calling strList.sublist(0, 3) \n" + firstThreeStr ); // returns first 3 elements of the list
}
}

In the code above, we have created a strList ArrayList with some elements.

First, we set the fromIndex as 0 and toIndex as the size of the list to get the complete list. The subList will return a list of elements from index 0 to the index list size -1.

strList.subList(0, strList.size())

Then, we get the first three elements of the strList by calling:

strList.subList(0, 3);

This will extract elements from index 0 to (3 - 1) . Therefore, the elements at index 0, 1, and 2 will be returned.

Free Resources