Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

vector
java
communitycreator

What is the vector.lastElement method in Java?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The lastElement() method of the Vector class returns the last element present in the Vector object.


Vector is a growable array of objects. Elements are mapped to an index.


Syntax


public E lastElement();

Return value

This method returns the last element of the Vector object. If the Vector object is empty then NoSuchElementException is thrown.

Code

import java.util.Vector;
class VectorLastElementExample {
public static void main( String args[] ) {
// Creating Vector
Vector<Integer> vector = new Vector<>();
// add elememts
vector.add(1);
vector.add(2);
vector.add(3);
System.out.println("The Vector is: " + vector);
// Print last element
System.out.println("The last element of the Vector is : " + vector.lastElement());
}
}

Explanation

In the code above, we created a Vector object and added three elements 1, 2, 3 using the add method. We then called the lastElement method on the vector object.


vector.lastElement();

This would return 3.

RELATED TAGS

vector
java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring