In Java, setSize(newSize) forces a Stack to hold exactly newSize elements. If the new size is larger, null elements are added on top. If it is smaller, elements are removed from the top until the size fits.
It is a Vector method, so it thinks in indexes: it keeps indexes 0 to newSize - 1 (the bottom part of the stack) and discards or creates everything above. That makes it handy for cutting a history down to its oldest entries, or for reserving slots you then fill with set().
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
Pass the number of elements the stack should have.
Java
Stack<String> stack = new Stack<>();
stack.push("a");
stack.push("b"); // [a, b]
stack.setSize(4); // [a, b, null, null] the top is null
stack.setSize(1); // [a] b and both nulls are gone
stack.setSize(0); // [] same as clear()
stack.setSize(-1); // throws ArrayIndexOutOfBoundsException
Call
What it does
stack.setSize(n), n > size()
Pads the top with null elements.
stack.setSize(n), n < size()
Drops elements from the top; the bottom n stay.
stack.setSize(0)
Empties the stack, like clear().
stack.setSize(stack.size() - 1)
Discards the top element without returning it.
Size and capacity are different things: setSize changes the number of elements; the internal array only grows when the new size does not fit.
Library declarations
Java
// java.util.Vector<E>, inherited by Stack<E>
public synchronized void setSize(int newSize)
reserved: [null, null, null]
filled: [bronze, silver, gold], top gold
setSize(-1): ArrayIndexOutOfBoundsException
after setSize(0): [], empty true
How It Works
Slots before values. On an empty stack, setSize(3) creates three null slots, so indexes 0 to 2 become valid for set.
Fill bottom to top. bronze goes in at index 0 and gold at index 2, which makes gold the top that peek() returns.
The limits. A negative size is rejected with ArrayIndexOutOfBoundsException, while setSize(0) is a valid way to empty the podium.
Frequently Asked Questions
It sets the number of elements. A larger size adds null elements on top; a smaller size removes elements from the top.
The ones with the highest indexes, which on a Stack are the most recently pushed elements at the top.
No. ensureCapacity only reserves room in the internal array and leaves size() unchanged. setSize changes size() and adds or removes elements.
It throws ArrayIndexOutOfBoundsException.
Growing the stack fills the new positions with null, and the last of them is now the top. The stack is not empty, so peek() returns that null instead of throwing.