Get Sublist from Vector

In the previous post, we have seen how to remove the element from a particular position. In this post, we will see how to get sublist from vector.

There is method ‘subList(int fromIndex,int toIndex)‘ which is used to get the sublist from vector.

Syntax:

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

It 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.
This method eliminates the need for explicit range operations (of the sort that commonly exist for arrays). Any operation that expects a List can be used as a range operation by operating on a subList view instead of a whole List. For example, the following idiom removes a range of elements from a List:
list.subList(from, to).clear();

Example:

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

public class VectorExmple {

	public static void main(String[] args) {
		
		Vector<String> car = new Vector<String>(3);   //it has capacity of 3
		car.addElement("BMW");
		car.addElement("Honda");
		car.addElement("Audi");
		car.addElement("Ferrari");
		car.addElement("Bugatti");
		
		System.out.println("All cars : "+car);
		
		List sublist = car.subList(1, 3); /* it returns sublist between fromIndex and (toIndex-1) */
		System.out.println("Sublist from vector 'car' : "+sublist);

	}
}

Output:

All cars :[BMW, Honda, Audi, Ferrari, Bugatti]
Sublist from vector ‘car’ :[Honda, Audi]


 

Questions/Suggestions
Have any question or suggestion for us?Please feel free to post in Q&A Forum
Avatar photo

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...