Vector subList() method in java

Let’s learn vector subList(int fromIndex, int toIndex) method in java.

Vector subList(int fromIndex, int toIndex) method in java

subList(int fromIndex, int toIndex) 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)

Parameters

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

Throws

IndexOutOfBoundsException – if an endpoint index value is out of range (fromIndex < 0 || toIndex > size)
IllegalArgumentException – if the endpoint indices are out of order (fromIndex > toIndex)

Example

import java.util.*;

class VectorSubListMethodDemo
{
   public static void main(String[] args) 
   {
      Vector<Integer> v = new Vector<Integer>();  
      v.add(2);
      v.add(3);  
      v.add(4);  
      v.add(5);  
      v.add(6);  
      v.add(7);   
      System.out.println("Vector elements : " + v);  
      // get subList of vector  
      List<Integer> l = v.subList(1, 3);  
      System.out.println("Vector after Sublist elements : " + l);          
   }
}

Output:

Vector elements : [2, 3, 4, 5, 6, 7]
Vector after Sublist elements : [3, 4]


import java.util.*;

class VectorSubListMethodDemo
{
   public static void main(String[] args) 
   {
      Vector<Integer> v = new Vector<Integer>();  
      v.add(2);
      v.add(3);  
      v.add(4);  
      v.add(5);  
      v.add(6);  
      v.add(7);   
      System.out.println("Vector elements : " + v);  
      // get subList of vector  
      List<Integer> l = v.subList(7, 9);  
      System.out.println("Vector after Sublist elements : " + l);          
   }
}

Output:

Vector elements : [2, 3, 4, 5, 6, 7]
Exception in thread “main” java.lang.IndexOutOfBoundsException: toIndex = 9
at java.base/java.util.AbstractList.subListRangeCheck(AbstractList.java:509)
at java.base/java.util.AbstractList.subList(AbstractList.java:499)
at java.base/java.util.Vector.subList(Vector.java:1121)
at ArraysInJava/com.collections.java.VectorSubListMethodDemo.main(VectorSubListMethodDemo.java:18)


Also read – abstraction in java