Java Stack - setElementAt() Method
The java.util.Stack.setElementAt() method is used to set the component at the specified index of the stack to be the specified object. The previous component at that position is discarded.
Syntax
public void setElementAt(E obj, int index)
Here, E is the type of element maintained by the container.
Parameters
obj |
Specify object to set with. |
index |
Specify index number of the component to set. |
Return Value
void type.
Exception
Throws IndexOutOfBoundsException, if the index is out of range.
Example:
In the example below, the java.util.Stack.setElementAt() method is used to set the element at the specified index of the stack to be 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.setElementAt(1000, 1); 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