The subList() method of AbstractList class in Java


The subList() method returns a part of this list between the specified fromIndex, inclusive, and toIndex, exclusive. Get a sublist using the method by setting the range as the two parameters.

The syntax is as follows.

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

Here, the parameter fromIndex is the low endpoint (inclusive) of the subList and toIndex is the high endpoint (exclusive) of the subList.

To work with the AbstractList class, import the following package.

import java.util.AbstractList;

The following is an example to implement subList() method of the AbstractlList class in Java.

Example

import java.util.ArrayList;
import java.util.AbstractList;
public class Demo {
   public static void main(String[] args) {
      AbstractList<Integer> myList = new ArrayList<Integer>();
      myList.add(5);
      myList.add(20);
      myList.add(35);
      myList.add(47);
      myList.add(55);
      myList.add(70);
      myList.add(100);
      myList.add(140);
      myList.add(180);
      myList.add(250);
      System.out.println("Elements in AbstractList = " + myList);
      List<Integer> list = myList.subList(5, 7);
      System.out.println("Sublist of AbstractList: "+ list);
   }
}

Output

Elements in AbstractList = [5, 20, 35, 47, 55, 70, 100, 140, 180, 250]
Sublist of AbstractList: [70, 100]

Updated on: 30-Jul-2019

74 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements