In this example we will see how to remove elements from Vector. We will be using remove(Object o) method of Vector API in order to remove specified elements.
public boolean remove(Object o)
: Removes the first occurrence of the specified element from Vector If the Vector does not contain the element, it is unchanged.
Example
In this example we are removing two String values from Vector of Strings. The steps are as follows:
1) Create a Vector
2) Add elements to the Vector using add(Element e) method of Vector class.
3) Remove elements using remove(Object o) method of Vector.
import java.util.Vector; public class RemoveFromVector { public static void main(String[] args) { // Creating a Vector of String Elements Vector<String> vector = new Vector<String>(); //Adding elements to the Vector vector.add("Harry"); vector.add("Steve"); vector.add("Vince"); vector.add("David"); vector.add("Matt"); System.out.println("Vector elements before remove(): "); for(int i=0; i < vector.size(); i++) { System.out.println(vector.get(i)); } // Removing Harry vector.remove("Harry"); // Removing Matt vector.remove("Matt"); 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(): Harry Steve Vince David Matt Vector elements after remove(): Steve Vince David
The remove(Object o) method returns boolean value. It returns true if specified element is present in Vector else false.
Leave a Reply