What is the Stack.insertElementAt() method in Java?
The
Stackclass is astack of objects. Last-In-First-Out (LIFO) The element inserted first is processed last and the element inserted last is processed first.
The insertElementAt() method of the Stack class can be used to add an element at the specific index of the Stack object. The index of the elements present at and after the passed index will be shifted upward (increased by 1).
Syntax
public void insertElementAt(E obj,int index)
Parameters
This method takes two parameters:
-
The element to be added to the
Stackobject. -
The index at which the new element is to be added. The index should be positive and less than or equal to the size of the
Stack, as shown below. Otherwise,ArrayIndexOutOfBoundsExceptionwill be thrown.
index >= 0 && index <= size()
Return value
insertElementAt() doesn’t return a value.
Code
The code below demonstrates the use of the Stack.insertElementAt() method:
import java.util.Stack;class InsertElementAt {public static void main( String args[] ) {// Creating StackStack<Integer> stack = new Stack<>();// add elememtsstack.push(10);stack.push(30);stack.push(50);System.out.println("The stack is: " + stack); // [10,30,50]stack.insertElementAt(20, 1); // [10,20,30,50]System.out.println("\nAfter calling insertElementAt(20,1). The stack is: " + stack);stack.insertElementAt(40, 3); // [10,20,30,40,50]System.out.println("\nAfter calling insertElementAt(40,3). The stack is: " + stack);}}
Please click the Run button above to see how the insertElementAt() method works.
Explanation
-
In line 5, we create a
Stackobject. -
In lines 8 to 10, we add three elements (
10,30,50) to the createdStackobject. -
In line 14, we use the
insertElementAt()method of theStackobject to add element20at index1. Now,stackwill contain10,20,30,50. -
In line 17, we use the
insertElementAt()method of theStackobject to add element40at index3. Now,stackwill contain10,20,30,40,50.