The
Stack
class 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 removeElementAt
method of the Stack
class can be used to remove the element at a specific index of the stack
object. The elements after the index will be shifted one index downward. The size of the stack
also decreases by 1
.
public void removeElementAt(int index)
The index
of the element is to be removed. The index should be positive and less than the size of the stack
object. Otherwise, ArrayIndexOutOfBoundsException
will be thrown.
index >= 0 && index < size()
This method doesn’t return any value.
Click the “Run” button below and see how the removeElementAt()
method works.
import java.util.Stack;class RemoveElementAt {public static void main( String args[] ) {// Creating a StackStack<Integer> stack = new Stack<>();// Adding elememts to the Stackstack.push(1);stack.push(2);stack.push(3);System.out.println("The stack is: " + stack);// Removing the element at index 1stack.removeElementAt(1);System.out.println("\nAfter removing the element at index 1, the stack is: " + stack);}}
In the code above:
In line 5, we created a Stack
object.
In lines 8 to 10, we added three elements (1,2,3
) to the created stack
object using the push
method.
In line 14, we used the removeElementAt()
method of the stack
object to remove the element present at index 1.