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
Vectorclass is a growable array of objects. You can use an integer index to access the elements ofVector, and the size of aVectorcan 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 VectorVector<Integer> vec = new Vector<>();// add elememtsvec.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
removeElementmethod of thevectorobject to remove the element1. The element1is present at index0and2. TheremoveElementmethod will only delete the first occurrence of the element1, so the element1at index0is deleted.