In this tutorial, we will learn how to remove elements from Vector using index. We will be using remove(int index) method of Vector class.
public E remove(int index)
: Removes the element at the specified position in this Vector. Shifts any subsequent elements to the left (subtracts one from their indices). Returns the element that was removed from the Vector.
Example
Index starts from 0 so if we are calling remove(2), it would remove the 3rd element from Vector.
import java.util.Vector; public class RemoveExample { public static void main(String[] args) { // Creating a Vector of Strings Vector<String> vector = new Vector<String>(); //Adding elements to the Vector vector.add("C++"); vector.add("Java"); vector.add("Cobol"); vector.add("C"); vector.add("Oracle"); System.out.println("Vector elements before remove(): "); for(int i=0; i < vector.size(); i++) { System.out.println(vector.get(i)); } // Removing 3rd element from Vector Object obj = vector.remove(2); System.out.println("\nElement removed from Vector is:"); System.out.println(obj); System.out.println("\nVector elements after remove():"); for(int i=0; i < vector.size(); i++) { System.out.println(vector.get(i)); } } }
Output:
Vector elements before remove(): C++ Java Cobol C Oracle Element removed from Vector is: Cobol Vector elements after remove(): C++ Java C Oracle
This was the example to remove Vector elements from specified index.
Leave a Reply