In this section, we will learn what the Vector subList() method is and how to use it in Java.
What is Java Vector subList() Method?
The Java Vector subList() method is used to get a view of a portion (sub-list) of vector object.
Note: the return value of this method is a List object.
We say a “view” not a copy! This means we can change the content in the List object (the return object of this method) and this change can be seen in the vector object itself as well. Basically, the two objects are backed by the same array of elements. So if one object done some changes, the other will see.
Java Vector subList() Method Syntax:
public List<E> subList(int fromIndex, int toIndex)
subList() Method Parameters:
The method takes two arguments:
- The first argument is the index number from which we want to get a view of the elements of the target vector object. The first argument is inclusive.
- The second argument is the endpoint of the last element we want to be in the view. Note this second argument is exclusive.
subList() Method Return Value:
The return value of this method is a List object that contains the view of the target vector object.
subList() Method Exceptions:
IndexOutOfBoundsException: we get this exception if either the endpoint or start-point index is out of the range.
IllegalArgumentException: We get this exception if the value of the first argument is bigger than the value of the second argument.
Example: using Vector subList() method
import java.util.Vector; import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args){ Vector <Integer> vector = new Vector<>(); vector.addElement(1); vector.addElement(2); vector.addElement(3); vector.addElement(4); vector.addElement(5); vector.addElement(6); vector.addElement(7); vector.addElement(8); List<Integer> list = new ArrayList<>(); list = vector.subList(3, vector.size()); list.set(0,1000); for (int i : vector){ System.out.println(i); } } }
Output:
1 2 3 1000 5 6 7 8