Java ArrayList subList() Method

What is ArrayList in java ?

Arraylist is a part of collection framework in java. It contains several inbuilt function like subList() method which can be found in the java.util.ArrayList Package. It implements the List interface of the collections framework.

Java ArrayList subList() Method :

Gives a view of the part of the list between the fromIndex and toIndex values that are specified. (The returned list is empty if the fromIndex and toIndex values are equal.) 

Since this list supports the returned list, any non-structural changes made to the returned list will also be reflected in the other way around. The returned list supports all of the optional list operations.

Syntax  :

public List subList(int fromIndex, int toIndex)

Parameters : 

  • fromIndex – low endpoint (inclusive) of the subList
  • toIndex – high endpoint (exclusive) of the subList

Return value:

This method returns a view of the specified range within this list.
java ArrayList subList() Method

Example 1 :  

Run

import java.util.ArrayList;
public class Main{
    public static void main(String[] args) {

        ArrayList list = new ArrayList<>();
        
        //Adding elements to the list
        list.add("A");      
        list.add("B");
        list.add("C");
        list.add("D");
        list.add("E");
        list.add("F");

        //Printing the subList from index 2 to 5
        System.out.println(list.subList(2, 5));
    }
}

Output :

[C, D, E]

Example 2 :

Run
import java.util.ArrayList;
public class Main{
    public static void main(String[] args) {

        ArrayList list = new ArrayList<>();
        
        //Adding elements to the list
        list.add("A");      
        list.add("B");
        list.add("C");
        list.add("D");
        list.add("E");
        list.add("F");

        //Printing the subList from index 2 to 7
        System.out.println(list.subList(2, 7));
    }
}

Output :

Exception in thread "main" java.lang.IndexOutOfBoundsException: toIndex = 7
        at java.base/java.util.AbstractList.subListRangeCheck(AbstractList.java:509)
        at java.base/java.util.ArrayList.subList(ArrayList.java:1108)
        at ArrayListSubList.main(ArrayListSubList.java:16)

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription