What is the Stack.removeAllElements 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 removeAllElements method of the Stack class removes all the elements present in the Stack object.
Syntax
public void removeAllElements()
This method doesn’t take any arguments and doesn’t return a value.
Code example
import java.util.Stack;class RemoveAll {public static void main( String args[] ) {// Creating StackStack<Integer> stack = new Stack<>();// add elememtsstack.add(1);stack.add(2);stack.add(3);System.out.println("The stack is: " + stack);stack.removeAllElements();System.out.println("After clearing the stack is : " + stack);}}
Click the
Runbutton on the code section above to see how theremoveAllElementsmethod works.
Explanation
In the code above:
-
Line 5: We create a
Stackobject. -
Lines 8 to 10: We use the
addmethod to add three elements (i.e. 1, 2, and 3) to theStackobject, as shown in the output of line 12. -
Line 14: We use the
removeAllElementsmethod to remove all the elements present in theStackobject. -
Line 15: After we call the
removeAllElementsmethod, theStackobject is empty.