What is the Vector.remove(Object) method in Java?
The
Vectorclass is a growable array of objects. The elements ofVectorcan be accessed using an integer index and the size of a Vector can be increased or decreased. Read more aboutVectorhere.
The remove method of the Vector class can be used to remove the first occurrence of a specific element from the vector object. The elements after the index will be shifted one index downward. The size of the vector also decreases by 1.
Syntax
public boolean remove(Object obj)
Argument
This method takes the element to be removed from the vector object as an argument.
Return value
This method returns true if the passed argument is present in the vector. Otherwise, false will be returned.
Code
import java.util.Vector;class remove {public static void main( String args[] ) {// Creating VectorVector<String> vector = new Vector<>();// add elememtsvector.add("hi");vector.add("hello");vector.add("hi");System.out.println("The Vector is: " + vector);vector.remove("hi");System.out.println("\nAfter removing element 'hi'. The Vector is: " + vector);}}
Please click the
Runbutton on the code section above to see how theremovemethod works.
Explanation
In the code above:
-
In line 5: We create a vector object.
-
In lines 8 to 10: We add three elements (
hi, hello, hi) to the created vector object. -
In line 14: We use the
removemethod of thevectorobject to remove the elementhi. The elementhiis present in index0and2. -
The
removemethod will delete the first occurrence of the elementhi, so the elementhiat index0is deleted.
If the element type of the
VectorisInteger, then using theremove(object)method will result in removing the element at the passed integer index. To handle this case, use theremoveElementmethod of thevectorobject.