In this example, we are gonna see how to get a sublist of elements from a Vector. We will be using subList() method of Vector class to do this.
More about this method from javadoc:
public List 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.Vector; import java.util.List; public class SublistExample { public static void main(String[] args) { // Step 1: Create a Vector Vector<String> vector = new Vector<String>(); // Step 2: Add elements vector.add("Item1"); vector.add("Item2"); vector.add("Item3"); vector.add("Item4"); vector.add("Item5"); vector.add("Item6"); /* The method subList(int fromIndex, int toIndex) * returns a List having elements of Vector * starting from index fromIndex * to (toIndex - 1). */ List subList = vector.subList(2,5); System.out.println("Sub list elements :"); for(int i=0; i < subList.size() ; i++){ System.out.println(subList.get(i)); } } }
Output:
Sub list elements : Item3 Item4 Item5
Rehan Usmani says
After running the above program . : Exception in thread “main” java.lang.Error: Unresolved compilation problems:
subList cannot be resolved
subList cannot be resolved
at controlFramework
VectorSubListExample
main(VectorSubListExample.java:16)
Rajeshwari says
change the variable name List sublist =vector.subList(2,5);