Stack add(int, Object) method in Java with Example
The add(int, Object) method of Stack Class inserts an element at a specified index in the Stack. It shifts the element currently at that position (if any) and any subsequent elements to the right (will change their indices by adding one).
void add(int index, Object element)
Parameters: This method accepts two parameters as described below.
- index: The index at which the specified element is to be inserted.
- element: The element which is needed to be inserted.
Return Value: This method does not return any value.
Exception: The method throws IndexOutOfBoundsException if the specified index is out of range of the size of the Stack.
Below program illustrates the working of java.util.Stack.add(int index, Object element) method:
The Stack is: [Geeks, for, Geeks, 10, 20] The new Stack is: [Geeks, for, Last, Geeks, Element, 10, 20]
The Stack is: [10, 20, 30, 40, 50] The new Stack is: [100, 10, 20, 200, 30, 40, 50]
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.