How to Get First and Last Element From the Vector in Java?
The first element in the Vector can be obtained using the firstElement() method of vector class that is represent util package. The last element in the Vector can be obtained using the lastElement() method of vector class that is also represent util package. Neither of these methods requires any parameters.
The first and last elements of the vector can be extracted in two ways:
- By directing getting the element at 0th index and size-1 index through get() method.
- By using firstElement() and lastElement() method.
Method 1: Getting elements at 0th and last index
We can use get() method:
- For first element, get the element at 0th index.
- For last element, get the element at (vector’s size-1)th index.
Java
import java.util.Vector;
public class Example {
public static void main(String args[])
{
Vector<Integer> vector = new Vector<>();
vector.add( 5 );
vector.add( 9 );
vector.add( 0 );
vector.add( 5 );
vector.add( 3 );
System.out.println( "The Vector Elements are: "
+ vector);
System.out.println(
"The First Element of the Vector is : "
+ vector.get( 0 ));
System.out.println(
"The Last Element of the Vector is : "
+ vector.get(vector.size() - 1 ));
}
}
|
Output
The Vector Elements are: [5, 9, 0, 5, 3]
The First Element of the Vector is : 5
The Last Element of the Vector is : 3
Method 2: Using firstElement() and lastElement() method
These two methods do not accept anything as parameters.
- firstElement() method gives the first element of the vector.
- lastElement() method gives the last element of the vector.
Java
import java.util.Vector;
public class Example {
public static void main(String args[])
{
Vector<Integer> vector = new Vector<>();
vector.add( 5 );
vector.add( 9 );
vector.add( 0 );
vector.add( 5 );
vector.add( 3 );
System.out.println( "The Vector Elements are: "
+ vector);
System.out.println(
"The First Element of the Vector is : "
+ vector.firstElement());
System.out.println(
"The Last Element of the Vector is : "
+ vector.lastElement());
}
}
|
Output
The Vector Elements are: [5, 9, 0, 5, 3]
The First Element of the Vector is : 5
The Last Element of the Vector is : 3
Last Updated :
17 Dec, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...