In Java, lastElement() returns the element at index size() - 1 of a Stack: the top, the element pushed most recently. Nothing is removed.
It reads the same element as peek(). The difference shows on an empty stack: lastElement() throws NoSuchElementException (it is a Vector method), while peek() throws EmptyStackException.
An instance method inherited from java.util.Vector (since Java 1.0). Stack does not override it: index 0 is the bottom of the stack and index size() - 1 is the top.
Syntax
Call it with no arguments to read the top.
Java
Stack<Integer> stack = new Stack<>();
stack.push(1);
stack.push(2);
stack.push(3); // [1, 2, 3]
int top = stack.lastElement(); // 3, same as stack.peek()
stack.pop();
int newTop = stack.lastElement(); // 2
new Stack<Integer>().lastElement(); // throws NoSuchElementException
Call
What it does
stack.lastElement()
The top element (index size() - 1).
stack.peek()
The same element; EmptyStackException when empty.
stack.firstElement()
The other end: the bottom.
stack.get(stack.size() - 1)
The same element through the List API.
lastElement is a constant-time read.
Library declarations
Java
// java.util.Vector<E>, inherited by Stack<E>
public synchronized E lastElement()
Catch what the method throws.topOf catches NoSuchElementException, the exception lastElement() uses for an empty stack.
peek needs a different catch. The same empty stack makes peek() throw EmptyStackException; neither class extends the other, so one catch block would not cover both.
The normal case. Once a job is pushed, topOf simply returns it: backup.
Frequently Asked Questions
The top element, the one pushed most recently. It is the same element peek() returns.
They read the same element. On an empty stack lastElement() throws NoSuchElementException and peek() throws EmptyStackException.
No. Use pop() to read and remove it.
No. lastElement() returns the top element; lastIndexOf(o) returns the index of the last occurrence of o.
peek() states the stack intent more clearly. lastElement() is useful when code treats the Stack as a Vector or List.