Get first and last elements from Vector in Java


The first element in the Vector can be obtained using the java.util.Vector.firstElement() method. The last element in the Vector can be obtained using the java.util.Vector.lastElement() method. Neither of these methods requires any parameters.

A program that demonstrates this is given as follows:

Example

 Live Demo

import java.util.Vector;
public class Demo {
   public static void main(String args[]) {
      Vector vec = new Vector();
      vec.add(4);
      vec.add(7);
      vec.add(2);
      vec.add(8);
      vec.add(6);
      System.out.println("The Vector elements are: " + vec);
      System.out.println("The first element of the Vector is : " + vec.firstElement());
      System.out.println("The last element of the Vector is : " + vec.lastElement());
   }
}

The output of the above program is as follows:

The Vector elements are: [4, 7, 2, 8, 6]
The first element of the Vector is : 4
The last element of the Vector is : 6

Now let us understand the above program.

The Vector is created. Then Vector.add() is used to add the elements to the Vector. Vector.firstElement() and Vector.lastElement() are used to get the first and last elements of the Vector respectively. These elements are displayed. A code snippet which demonstrates this is as follows:

Vector vec = new Vector();
vec.add(4);
vec.add(7);
vec.add(2);
vec.add(8);
vec.add(6);
System.out.println("The Vector elements are: " + vec);
System.out.println("The first element of the Vector is : " + vec.firstElement());
System.out.println("The last element of the Vector is : " + vec.lastElement());

Vikyath Ram
Vikyath Ram

A born rival

Updated on: 30-Jul-2019

447 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements