The setElementAt() method of Java Stack is used to set the component at the specified index of this vector to be the specified object. The previous component at that position is discarded. The index must be a value greater than or equal to 0 and less than the current size of the vector.
public void setElementAt(E element, int index)
Parameters: This function accepts two parameters as shown in the above syntax and described below.
- element: It is the new element by which the existing element will be replaced and is of the same object type as the stack.
- index: This is of integer type and refers to the position of the element that is to be replaced from the stack.
Return Value: This method do not return anything.
Exception: This method throws ArrayIndexOutOfBoundsException if the index is out of range (index = size())
Below program illustrate the Java.util.Stack.setElementAt() method:
Stack:[Geeks, for, Geeks, 10, 20] Geeks replaced with GFG The new Stack is:[Geeks, for, GFG, 10, 20]
Example 2: To demonstrate ArrayIndexOutOfBoundsException
Stack:[Geeks, for, Geeks, 10, 20] Trying to replace 10th element with GFG java.lang.ArrayIndexOutOfBoundsException: 10 >= 5
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.