Vector
Remove Vector elements using index example
In this example we shall show you how to remove elements from a Vector using index. To remove an element from a Vector using index one should perform the following steps:
- Create a new Vector.
- Populate the vector with elements, with
add(E e)
API method of Vector. - Remove an element from the Vector. Invoke
remove(int index)
API method of Vector, with an index as parameter. The method removes the element at the specified position in this Vector and shifts any subsequent elements to the left (subtracts one from their indices). It returns the element that was removed from the Vector,
as described in the code snippet below.
package com.javacodegeeks.snippets.core; import java.util.Vector; public class RemoveElementFromVectorIndex { 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"); /* To remove an element from the specified index of Vector use Object remove(int index) method. The method returns a reference to the element that was removed. */ Object obj = vector.remove(2); System.out.println(obj + " is removed from Vector"); System.out.println("Elements in Vector :"); for(int i=0; i < vector.size(); i++) System.out.println(vector.get(i)); } }
Output:
element_3 is removed from Vector
Elements in Vector :
element_1
element_2
This was an example of how to remove elements from a Vector using index in Java.