In Java, set(index, element)replaces the element at a position in a Stack and returns the element that was there before. The size does not change.
Index 0 is the bottom and size() - 1 is the top, so stack.set(stack.size() - 1, x) swaps out the top element without a pop and a push. The legacy setElementAt() does the same job but returns nothing.
An instance method inherited from java.util.Vector (since Java 1.2). Stack does not override it: index 0 is the bottom of the stack and index size() - 1 is the top.
Syntax
Pass the index first, then the new element; keep the returned old value if you need it.
Java
Stack<String> stack = new Stack<>();
stack.push("hte");
stack.push("cat"); // [hte, cat]
String old = stack.set(0, "the"); // old is "hte", stack is [the, cat]
stack.set(stack.size() - 1, "dog"); // replaces the top: [the, dog]
stack.set(2, "x"); // throws ArrayIndexOutOfBoundsException
Call
What it does
stack.set(i, e)
Replaces the element at i; returns the old one.
stack.set(stack.size() - 1, e)
Replaces the top in one step.
stack.set(0, e)
Replaces the bottom.
stack.setElementAt(e, i)
The legacy equivalent: arguments reversed, no return value.
set is a constant-time array write; nothing shifts.
Library declarations
Java
// java.util.Vector<E>, inherited by Stack<E>
public synchronized E set(int index, E element)
Parameters
Parameter
Description
index (int)
Position to replace, from 0 (bottom) to size() - 1 (top).
element (E)
The new value; null is allowed.
Return Value
Return Value
Description
E
The previous element at that index (it can be null).
No slot 3 yet. With three elements the valid indexes are 0 to 2, so set(3, "D") throws; catching IndexOutOfBoundsException also covers the concrete ArrayIndexOutOfBoundsException.
Grow first.push("D") creates index 3 at the top of the stack.
Now set succeeds.set(3, "E") replaces D with E and returns D; the concatenation runs the call before it prints the stack.
Frequently Asked Questions
The element that was previously at that index. The new element takes its place and the size stays the same.
size() - 1. Index 0 is the bottom, the first element pushed.
No. It only replaces existing elements. An index equal to size() or larger throws an index exception; use push or add instead.
set(index, element) returns the old value and follows the List argument order. setElementAt(element, index) is the legacy Vector version with reversed arguments and no return value.
No. Only the value at one index changes; every other element stays where it was.