Stack set() method in Java with Example
The set() method of Java Stack is used to replace any particular element in the stack created using the Stack class with another element. This can be done by specifying the position of the element to be replaced and the new element in the parameter of the set() method.
public E set(int index, Object element)
Parameters: This function accepts two parameters as shown in the above syntax and described below.
- index: This is of integer type and refers to the position of the element that is to be replaced from the stack.
- element: It is the new element by which the existing element will be replaced and is of the same object type as the stack.
Return Value: The method returns the previous value from the stack that is replaced with the new value.
Exception: This method throws following exceptions:
- UnsupportedOperationException: if the set operation is not supported by this stack
- ClassCastException: if the class of the specified element prevents it from being added to this stack
- NullPointerException: if the specified element is null and this stack does not permit null elements
- IllegalArgumentException: if some property of the specified element prevents it from being added to this stack
- IndexOutOfBoundsException: if the index is out of range (index = size())
Below program illustrate the Java.util.Stack.set() method:
Stack:[Geeks, for, Geeks, 10, 20] The Object that is replaced is: Geeks The Object that is replaced is: 20 The new Stack is:[Geeks, for, GFG, 10, 50]
Example 2: To demonstrate IndexOutOfBoundException
Stack:[Geeks, for, Geeks, 10, 20] Trying to replace 10th element with GFG java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 10