- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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());
- Related Articles
- Get first and last elements from Java LinkedList
- How to get first and last elements from ArrayList in Java?
- Java Program to Get First and Last Elements from an Array List
- Python program to get first and last elements from a tuple
- Get first and last elements of a list in Python
- Get all rows apart from first and last in MySQL
- Delete first and last element from a LinkedList in Java
- Get last key from NavigableMap in Java
- Get last entry from NavigableMap in Java
- Get last N elements from given list in Python
- Python Program to get first and last element from a Dictionary
- Java Program to Interchange Elements of First and Last in a Matrix Across Rows
- Java Program to Interchange Elements of First and Last in a Matrix Across Columns
- Golang program to get the first and last element from a slice
- Get first key from NavigableMap in Java

Advertisements