Java Stack setSize() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
Inherited from Vector

Definition

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
CallWhat 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)

Parameters

ParameterDescription
newSize (int)The new number of elements; must not be negative.

Return Value

Return ValueDescription
voidNothing.

Compare with Similar Methods

Methods that change how many elements there are:

MethodHow it differs
size()Reads the number of elements; setSize changes it.
clear()The same as setSize(0).
pop()Removes one element from the top and returns it.
set(i, e)Fills a slot that setSize created.

Java Examples

Example 1 — Grow a Stack with Empty Slots

Make room for two more jars on a pantry shelf and look at what fills the gap.

Java
import java.util.Stack;

public class StackSetSizeGrow {
    public static void main(String[] args) {
        Stack<String> shelf = new Stack<>();
        shelf.push("jam");
        shelf.push("honey");

        shelf.setSize(4);
        System.out.println("shelf: " + shelf);
        System.out.println("size: " + shelf.size());
        System.out.println("top is null: " + (shelf.peek() == null));
    }
}

How It Works

  1. Two new slots. Growing from 2 to 4 appends two null elements above honey.
  2. Nulls are real elements. size() counts them, so it reports 4.
  3. A null top, not an empty stack. peek() returns null without throwing, because the stack is not empty; it just has null on top.

Example 2 — Keep Only the Oldest Saves

Shrink a stack of five saved games to two and see which ones survive.

Java
import java.util.Stack;

public class StackSetSizeTruncate {
    public static void main(String[] args) {
        Stack<String> saves = new Stack<>();
        for (int i = 1; i <= 5; i++) {
            saves.push("save" + i);
        }
        System.out.println("before: " + saves);

        saves.setSize(2);
        System.out.println("after setSize(2): " + saves);
        System.out.println("new top: " + saves.peek());
    }
}

How It Works

  1. Five saves pushed. save5 is the newest and sits on top.
  2. The top is cut off. setSize(2) keeps indexes 0 and 1 and discards save3, save4, and save5, the three most recent.
  3. The oldest survive. save2 becomes the top; to keep the newest entries instead, remove from the bottom with remove(0).

Example 3 — Reserve Slots, Then Fill Them

Create three empty podium places, fill them by index, and test the limits of setSize.

Java
import java.util.Stack;

public class StackSetSizeSlots {
    public static void main(String[] args) {
        Stack<String> podium = new Stack<>();
        podium.setSize(3);
        System.out.println("reserved: " + podium);

        podium.set(0, "bronze");
        podium.set(1, "silver");
        podium.set(2, "gold");
        System.out.println("filled: " + podium + ", top " + podium.peek());

        try {
            podium.setSize(-1);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("setSize(-1): ArrayIndexOutOfBoundsException");
        }
        podium.setSize(0);
        System.out.println("after setSize(0): " + podium + ", empty " + podium.empty());
    }
}

How It Works

  1. Slots before values. On an empty stack, setSize(3) creates three null slots, so indexes 0 to 2 become valid for set.
  2. Fill bottom to top. bronze goes in at index 0 and gold at index 2, which makes gold the top that peek() returns.
  3. 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.

Next: size()

Count the elements on the stack.

size() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

12 people found this page helpful