In Java, size() returns the number of elements currently on a Stack. Every push adds one, every pop removes one, and null elements count too.
The size is not the capacity, which is the length of the internal array that Vector manages (readable with capacity()). The size also gives you the index of the top element: size() - 1.
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 size with no arguments.
Java
Stack<String> stack = new Stack<>();
int a = stack.size(); // 0
stack.push("x");
stack.push("y");
int b = stack.size(); // 2
int topIndex = b - 1; // 1, the index of "y"
stack.pop();
int c = stack.size(); // 1
Call
What it does
stack.size()
The number of elements.
stack.size() - 1
The index of the top element.
stack.size() == 0
The same as empty() and isEmpty().
stack.capacity()
Room in the internal array, not the element count.
size() is constant time: Vector keeps a running count of its elements.
Library declarations
Java
// java.util.Vector<E>, inherited by Stack<E>
public synchronized int size()
Room for ten.new Stack<>() calls Vector's no-argument constructor, documented to start with an internal array of 10 slots, while the size is 0.
Full but not grown. After ten pushes, size and capacity are both 10: every slot is in use.
Doubling on overflow. The eleventh push needs one more slot, so the array grows to 20 (a capacity increment of 0 means "double"), while the size is simply 11.
Example 3 — Keep at Most Three Undo Steps
Use size() to cap an undo history and drop the oldest action when it gets too long.
Java
import java.util.Stack;
public class StackSizeLimit {
static final int MAX = 3;
public static void main(String[] args) {
Stack<String> undo = new Stack<>();
String[] actions = {"cut", "paste", "bold", "italic", "underline"};
for (String a : actions) {
undo.push(a);
if (undo.size() > MAX) {
String dropped = undo.remove(0);
System.out.println("dropped oldest: " + dropped);
}
}
System.out.println("kept " + undo.size() + ": " + undo);
}
}