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.

1

publicEfirstElement()

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

1

publicElastElement()

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

importjava.util.Vector;

publicclassJavaVectorGetFirstLastElementsExample{

publicstaticvoidmain(String[]args){

Vector<String>vColors=newVector<String>();

vColors.add("Red");

vColors.add("Green");

vColors.add("Blue");

/*

* To get the first element, use

* the firstElement method

*/

System.out.println("First element: "+vColors.firstElement());

/*

* To get the last element, use

* the lastElement method

*/

System.out.println("Last element: "+vColors.lastElement());

}

}

Output

1

2

First element: Red

Last element: Blue

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.

About the author

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.