Open In App

AbstractSequentialList subList() method in Java with Example

The subList() method of AbstractSequentialList in Java is used to get a view of the portion of this list between the specified 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 non-structural 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:



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

Parameters: These method takes two parameters:

Return Value: This method returns a view of the specified range within this list
Exception: This method throws:



Below examples illustrates AbstractSequentialList.subList() method:

Example 1:




// Java program to demonstrate the
// working of subList() method
  
import java.util.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // creating an AbstractSequentialList
        AbstractSequentialList<Integer> arr
            = new LinkedList<Integer>();
  
        // use add() method
        // to add values in the list
        arr.add(1);
        arr.add(2);
        arr.add(3);
        arr.add(12);
        arr.add(9);
        arr.add(13);
  
        // prints the list before removing
        System.out.println("AbstractSequentialList: "
                           + arr);
  
        // Getting subList of 1st 2 elements
        // using subList() method
        System.out.println("subList of 1st 2 elements: "
                           + arr.subList(0, 2));
    }
}

Output:
AbstractSequentialList: [1, 2, 3, 12, 9, 13]
subList of 1st 2 elements: [1, 2]

Example 2:




// Java program to demonstrate the
// working of subList() method
  
import java.util.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // creating an AbstractSequentialList
        AbstractSequentialList<Integer> arr
            = new LinkedList<Integer>();
  
        // use add() method
        // to add values in the list
        arr.add(1);
        arr.add(2);
        arr.add(3);
        arr.add(12);
        arr.add(9);
        arr.add(13);
  
        // prints the list before removing
        System.out.println("AbstractSequentialList: "
                           + arr);
  
        System.out.println("Trying to get "
                           + "subList of 11th elements: ");
  
        try {
  
            // Getting subList of 10th
            // using subList() method
            arr.subList(10, 11);
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}

Output:
AbstractSequentialList: [1, 2, 3, 12, 9, 13]
Trying to get subList of 11th elements: 
java.lang.IndexOutOfBoundsException: toIndex = 11

Article Tags :