Vector

Remove Vector element example

This is an example of how to remove an element from a Vector. We are using the remove(Object o) API method of Vector. Removing an element from a Vector implies that you should:

  • Create a new Vector.
  • Populate the vector with elements, with add(E e) API method of Vector.
  • Remove an element from the Vector, using remove(Object o) API method. The method removes the first occurrence of the specified element in this Vector. If the Vector does not contain the element, it is unchanged.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;
 
import java.util.Vector;
 
public class RemoveElementFromVector {
 
  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");
 
    System.out.println("Vector contents : " + vector);

    // boolean remove(Object o) method removes the specific object from the Vector if present and returns true, false otherwise
    boolean removed = vector.remove("element_2");
  
    System.out.println("Vector contents after removal of element_2 : " + vector);
 
  }
}

Output:

Vector contents : [element_1, element_2, element_3]
Vector contents after removal of element_2 : [element_1, element_3]

 
This was an example of how to remove an element from a Vector in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button