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 removeAllElements
method of the Stack class removes all the elements present in the Stack
object.
public void removeAllElements()
This method doesn’t take any arguments and doesn’t return a value.
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
Run
button on the code section above to see how theremoveAllElements
method works.
In the code above:
Line 5: We create a Stack
object.
Lines 8 to 10: We use the add
method to add three elements (i.e. 1, 2, and 3) to the Stack
object, as shown in the output of line 12.
Line 14: We use the removeAllElements
method to remove all the elements present in the Stack
object.
Line 15: After we call the removeAllElements
method, the Stack
object is empty.