Java Vector Remove Elements Example

This example shows how to remove elements from Vector in Java. This example also shows how to remove elements from Vector using remove, removeElement, and removeElementAt methods.

How to remove elements from Vector in Java?

There are several ways using which we can remove elements from Java Vector as given below.

1. How to remove an element at a specific index from Vector using remove and removeElementAt methods?

The Vector remove method removes an element located at the specified index of this vector object.

It returns the element that was removed from the vector object.

The removeElementAt method is similar to this remove method and removes an element from the vector at the specified index.

The only difference is in the return type, the remove method returns the element that was removed while the return type of the removeElementAt method is void.

2. How to remove a specific element from Vector using the remove and removeElement methods?

The overloaded remove method takes an object as an argument instead of the index and removes the first occurrence of the specified element from the vector.

It returns true if the specified element was found and removed from this vector object, false otherwise.

Output

The removeElement method is similar to this remove method and removes the first occurrence of the element from this vector object.

It also returns true if the specified element was found and removed from this vector object, false otherwise.

How to remove an object of a custom class from the Vector?

If the Vector elements are objects of a custom class, then theĀ remove and removeElement methods will not work properly if the custom class has not overridden the equals and hashCode methods as given below.

Output

As we can see from the output, even if the object element exists in the vector, the remove method returned false. To solve this problem, we need to override the equals and hashCode methods in the Student custom class.

Output

Please also visit how to clear or remove all elements from the Vector example to know more.

This example is a part of the Vector in Java Tutorial with Examples.

Please let me know your views in the comments section below.

References:
Java 8 Vector Documentation

About the author

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *