Skip to content

Get First and Last Elements from Java Vector Example

This example shows how to get the first and last elements from the Vector in Java. This example also shows how to get the first and last elements using the firstElement, lastElement, and get methods.

How to get the first and last element from the Vector in Java?

There are a couple of ways using which we can get the first element or last element from the vector object.

1. Using the firstElement and lastElement methods

The Vector firstElement method returns the first element of the vector object.

Similarly, the Vector lastElement method returns the last element of this vector object.

Output

Important Note:

The firstElement and lastElement methods throw NoSuchElementException exception if the vector is empty. Always make sure to check if the vector is empty or not before calling any of these methods to avoid this exception.

Output

2. Using the get method and element index

Since the Vector is an index-based data structure, we can use the Vector get method along with the index to access first and last vector elements.

The vector index starts from 0 and ends at the vector size – 1 index. So the first element of the vector object is located at index 0 while the last element is located at the vector size – 1 index.

Output

The get method throws ArrayIndexOutOfBoundsException exception if the specified index < 0 or specified index >= vector size.

Output

Always make sure that the vector is not empty to avoid this exception as given below.

Output

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

Leave a Reply

Your email address will not be published.