Java Utility Library

Java Vector - removeElement() Method



The java.util.Vector.removeElement() method is used to remove the first occurrence of the element from the vector, if it is present. It shifts any subsequent elements to the left by subtracting one from their indices. Every removal of element results into reducing the vector size by one unless the vector is empty.

Syntax

public boolean removeElement(Object obj)

Parameters

obj Specify the element which need to be removed from the vector, if present.

Return Value

Returns true if this vector contained the specified element, false otherwise.

Exception

NA.

Example:

In the example below, the java.util.Vector.removeElement() method is used to removeElement the first occurrence of specified element from the given vector.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a vector
    Vector<Integer> MyVector = new Vector<Integer>();

    //populating vector
    MyVector.add(10);
    MyVector.add(20);
    MyVector.add(30);
    MyVector.add(20);
    MyVector.add(20);

    //printing vector
    System.out.println("MyVector contains: " + MyVector);

    //remove the first occurrence of 20
    MyVector.removeElement(20);

    //printing vector
    System.out.println("MyVector contains: " + MyVector);
  }
}

The output of the above code will be:

MyVector contains: [10, 20, 30, 20, 20]
MyVector contains: [10, 30, 20, 20]

❮ Java.util - Vector