Java Utility Library

Java Vector - subList() Method



The java.util.Vector.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.Vector.subList() method returns a view of the portion of the given vector.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a vector
    Vector<Integer> MyVector = new Vector<Integer>();

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

    //creating a portion view of the vector
    List MyList = MyVector.subList(2, 5);

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

The output of the above code will be:

MyVector contains: [10, 20, 30, 40, 50, 60, 70]
MyList contains: [30, 40, 50]

❮ Java.util - Vector