Java Vector subList(int fromIndex, int toIndex) Method Example

The subList(int fromIndex,int toIndex) method of java.util.Vector class will return 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.

Signature

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

This method returns a view of the portion of this list between the specified fromIndex(inclusive) and toIndex(exclusive), If fromIndex and toIndex are equal, then the returned list will be empty. Throws IndexOutOfBoundsException if an endpoint index value is out of range (fromIndex < 0 || toIndex > size) and
IllegalArgumentException if the endpoint indices are out of order (fromIndex > toIndex)

Example

The following example shows the usage of java.util.Vector.subList(fromIndex,toIndex) method.

import java.util.List;
import java.util.Vector;

public class VectorExample 
{
    public static void main(String[] args) { 
        // Create Vector vector1 object
        Vector vector1 = new Vector();
        
        //adding elements to vector1
        vector1.add("Element1");
        vector1.add("Element2");
        vector1.add("Element3");
        vector1.add("Element4");
        vector1.add("Element5");
        vector1.add("Element6");
        vector1.add("Element7");
        
        System.out.println("**Contents of vector1**");
        for(String val: vector1)
        {
            System.out.println(val);
        }
        
       //Sublist to List
        List list1 = vector1.subList(2,5);
        System.out.println("**Contents of list1**");
        for(String val: list1)
        {
            System.out.println(val);
        }
   }
}

Output

**Contents of vector1**
Element1
Element2
Element3
Element4
Element5
Element6
Element7
**Contents of list1**
Element3
Element4
Element5

Leave a Reply

Your email address will not be published. Required fields are marked *