What is the Vector.removeElement method in Java?

The removeElement method of the Vector class removes the first occurrence of a specific element from the vector object on which the method is invoked.

The elements after the index will be shifted one index downward. The size of the vector also decreases by 1.

The Vector class is a growable array of objects. You can use an integer index to access the elements of Vector, and the size of a Vector can be increased or decreased.

Syntax

public boolean removeElement(Object obj)

Parameters

  • obj: The element to be removed from the vector object.

Return value

This method returns true if the element to be removed is present and successfully removed from the vector. Otherwise, it returns false.

Code

import java.util.Vector;
class RemoveElement {
public static void main( String args[] ) {
// Creating Vector
Vector<Integer> vec = new Vector<>();
// add elememts
vec.add(1);
vec.add(2);
vec.add(1);
System.out.println("The Vector is: " + vec);
vec.removeElement(1);
System.out.println("\nAfter removing element '1'. The Vector is: " + vec);
}
}

Explanation

In the code above:

  • In line 5: We create a vector object, vec.

  • In lines 8 to 10: We add three elements (1,2,1) to the created vector object.

  • In line 14: We use the removeElement method of the vector object to remove the element 1. The element 1 is present at index 0 and 2. The removeElement method will only delete the first occurrence of the element 1, so the element 1 at index 0 is deleted.

Free Resources