Remove First or Last Element from Vector in Java Example

This example shows how to remove the first or last element of the Vector in Java. This example also shows how to remove the first or last element from the vector using various methods.

How to remove the first or the last element from Vector in Java?

How to remove the first element from the vector?

The remove method of the Vector class removes the element at the specified position of the vector object.

This method removes and returns the element at the specified position from the vector object.

The vector elements start from the index so to remove the first element from the vector object, we need to pass 0 as the index in this method.

Output

How to remove the last element from the vector?

The vector elements start at index 0 and end at vector size – 1 index.┬áTo remove the last element from the vector, we will pass the vector size – 1 index in the remove method as given below.

Output

The remove method throws ArrayIndexOutOfBoundsException exception if the specified index is out of the range i.e. if the specified index is less than 0 or the specified index is greater than or equal to the vector size.

Output

Here, the vector is empty so the size of the vector is 0. We tried to remove the vector element using index 0 that is out of the range.

In order to avoid getting this exception, always make sure to check if the vector is empty before removing elements using the remove method and an index as given below.

Output

This example is a part of the Java Vector 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 *