Java Stack setElementAt() Method

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

Definition

In Java, setElementAt(obj, index) is the legacy Vector method that overwrites the element at a position of a Stack. The old element is discarded and nothing is returned.

It is the older twin of set(index, element): same effect, but the element comes first, the index second, and the return type is void. Like set, it can only replace elements that already exist.

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 new element first, then the index to overwrite.

Java
Stack<String> stack = new Stack<>();
stack.push("north");
stack.push("east");
stack.push("south");               // [north, east, south]
stack.setElementAt("west", 1);     // [north, west, south]
stack.set(1, "west");              // same change, List order, returns the old value
stack.setElementAt("x", 3);        // throws ArrayIndexOutOfBoundsException
CallWhat it does
stack.setElementAt(e, i)Overwrites index i with e; returns nothing.
stack.setElementAt(e, stack.size() - 1)Overwrites the top.
stack.setElementAt(e, 0)Overwrites the bottom.
E old = stack.set(i, e)The List version, for when you need the old value.

Like set, it is a constant-time write into the internal array.

Library declarations
Java
// java.util.Vector<E>, inherited by Stack<E>
public synchronized void setElementAt(E obj, int index)

Parameters

ParameterDescription
obj (E)The new element; null is allowed.
index (int)Position to overwrite, from 0 (bottom) to size() - 1 (top).

Return Value

Return ValueDescription
voidNothing; the previous element is lost unless you read it first.

Compare with Similar Methods

Methods that read or write one position:

MethodHow it differs
set(i, e)The same replacement in (index, element) order; returns the old element.
insertElementAt(e, i)The same argument order, but it inserts instead of replacing.
elementAt(i)The matching legacy read method.

Java Examples

Example 1 — Rename a Drawing Layer

A drawing app keeps its layers in a stack; overwrite the middle layer and report the change.

Java
import java.util.Stack;

public class StackSetElementAtDemo {
    public static void main(String[] args) {
        Stack<String> layers = new Stack<>();
        layers.push("background");
        layers.push("sketch");
        layers.push("ink");

        String before = layers.elementAt(1);
        layers.setElementAt("color", 1);
        System.out.println("index 1: " + before + " -> " + layers.elementAt(1));
        System.out.println("layers: " + layers);
    }
}

How It Works

  1. Save the old value yourself. setElementAt returns nothing, so the program reads index 1 with elementAt(1) before overwriting it.
  2. Element, then index. setElementAt("color", 1) overwrites the sketch layer in the middle of the drawing.
  3. Neighbors untouched. background stays at the bottom and ink stays on top; the stack still has three layers.

Example 2 — Double Every Combo Value in Place

Walk a stack of combo multipliers from bottom to top and double each one.

Java
import java.util.Stack;

public class StackSetElementAtLoop {
    public static void main(String[] args) {
        Stack<Integer> combo = new Stack<>();
        combo.push(3);
        combo.push(5);
        combo.push(8);

        for (int i = 0; i < combo.size(); i++) {
            combo.setElementAt(combo.elementAt(i) * 2, i);
        }
        System.out.println("doubled: " + combo);
        System.out.println("top: " + combo.peek());
    }
}

How It Works

  1. Visit every index. The loop runs from the bottom (index 0) to the top (index 2), reading each value with elementAt(i).
  2. Value first, index second. setElementAt(value * 2, i) writes the doubled number back into the same slot; on an Integer stack, swapped arguments would still compile, so keep the order in mind.
  3. Same shape, new values. 3, 5, 8 become 6, 10, 16, and the top is now 16.

Example 3 — Capacity Is Not Size

A new stack has room for 10 elements, yet setElementAt refuses index 2 on a two-element stack.

Java
import java.util.Stack;

public class StackSetElementAtBounds {
    public static void main(String[] args) {
        Stack<String> seats = new Stack<>();
        seats.push("Ana");
        seats.push("Ben");

        System.out.println("capacity " + seats.capacity() + ", size " + seats.size());
        try {
            seats.setElementAt("Cy", 2);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("setElementAt(Cy, 2): ArrayIndexOutOfBoundsException");
        }
        seats.push("Cy");
        seats.setElementAt("Cyd", 2);
        System.out.println("seats: " + seats);
    }
}

How It Works

  1. Room is not the same as size. A new stack has capacity 10 (the documented default of Vector's no-argument constructor), but only indexes below size(), here 0 and 1, hold elements.
  2. Index 2 is out of range. setElementAt("Cy", 2) throws ArrayIndexOutOfBoundsException because the method only overwrites existing elements.
  3. Push, then overwrite. After push("Cy") index 2 exists, so changing it to Cyd succeeds.

Frequently Asked Questions

Both replace the element at an index. setElementAt(element, index) returns nothing; set(index, element) returns the old element and uses the List argument order.
It is a Vector method from Java 1.0, designed before the List interface existed. List methods later standardized on putting the index first.
ArrayIndexOutOfBoundsException, when the index is negative or not less than size().
No. It only overwrites. Use push(), add(), or insertElementAt() to add an element.
Prefer set(index, element): it returns the old value and works with any List.

Next: setSize()

Grow with null elements or cut elements off the top.

setSize() 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.

11 people found this page helpful