Skip to content

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

Leave a Reply

Your email address will not be published.