Java Utility Library

Java Stack - set() Method



The java.util.Stack.set() method is used to replaces the element at the specified index in the stack with the specified element.

Syntax

public E set(int index, E element)

Here, E is the type of element maintained by the container.


Parameters

index Specify index number of the element to replace.
element Specify element to replace with.

Return Value

Returns the element at specified index of the stack.

Exception

Throws IndexOutOfBoundsException, if the index is out of range.

Example:

In the example below, the java.util.Stack.set() method is used to replace the element at the specified index in the stack with the specified element.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a stack
    Stack<Integer> MyStack = new Stack<Integer>();

    //populating stack
    MyStack.push(10);
    MyStack.push(20);
    MyStack.push(30);
    MyStack.push(40);
    MyStack.push(50);

    System.out.println("Before method call, MyStack contains: " + MyStack);
    MyStack.set(1, 1000);
    System.out.println("After method call, MyStack contains: " + MyStack);    
  }
}

The output of the above code will be:

Before method call, MyStack contains: [10, 20, 30, 40, 50]
After method call, MyStack contains: [10, 1000, 30, 40, 50]

❮ Java.util - Stack