Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What is the Vector.remove(Object) method in Java?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The Vector class is a growable array of objects. The elements of Vector can be accessed using an integer index and the size of a Vector can be increased or decreased. Read more about Vector here.

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 Vector
Vector<String> vector = new Vector<>();
// add elememts
vector.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 Run button on the code section above to see how the remove method 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 remove method of the vector object to remove the element hi. The element hi is present in index 0 and 2.

  • The remove method will delete the first occurrence of the element hi, so the element hi at index 0 is deleted.

If the element type of the Vector is Integer, then using the remove(object) method will result in removing the element at the passed integer index. To handle this case, use the removeElement method of the vector object.

RELATED TAGS

java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring