Vector

Get sub list of Vector example

This is an example of how to get the sub list of a Vector. The Vector API provides the subList(int fromIndex, int toIndex) method. Getting a Vector sub list implies that you should:

  • Create a new Vector.
  • Populate the vector with elements, with add(E e) API method of Vector.
  • Invoke subList(int fromIndex, int toIndex) method of Vector. The method returns a List object containing elements from startIndex to endIndex - 1 of the original Vector. The sub List returned is backed by the original Vector. So any changes made to the sub list will also be reflected to the original Vector. To check if this is true remove an element from the sub list and check that it is removed from the original Vector also.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;
 
import java.util.Vector;
import java.util.List;
 
public class SubListVector {
 
  public static void main(String[] args) {
 
    // Create a Vector and populate it with elements
    Vector vector = new Vector();
    vector.add("element_1");
    vector.add("element_2");
    vector.add("element_3");
    vector.add("element_4");
    vector.add("element_5");
 
    /*

 Use the List subList(int startIndex, int endIndex) operation 

 to get a sub list of the original Vector. This method 

 returns an List object containing elements from startIndex 

 to endIndex - 1 of the original Vector
    */
    List subList = vector.subList(1,3);
 
    System.out.println("Elements in sub list :");
    for(int i=0; i < subList.size() ; i++)

System.out.println(subList.get(i));
 
    /*

Sub List returned is backed by original Vector. So any

changes made to sub list will also be reflected to the 

original Vector. We will test that by removing an element 

from the sub list and check that it is removed from the original 

Vector also
    */
    Object obj = vector.remove(0);
    System.out.println(obj + " is removed from sub list");
 
    System.out.println("Elements in Vector :");
    for(int i=0; i < vector.size() ; i++)

System.out.println(vector.get(i));

  }
 
}

Output:

Elements in sub list :
element_2
element_3
element_1 is removed from sub list
Elements in Vector :
element_2
element_3
element_4
element_5

 
This was an example of how to get the sub list of a Vector in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button