Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What is the Stack.removeAllElements method in Java?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The Stack class is a Last-In-First-Out (LIFO)The element inserted first is processed last and the element inserted last is processed first. stack of objects.

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 Stack
        Stack<Integer> stack = new Stack<>();

        // add elememts 
        stack.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 the removeAllElements method works.

Explanation

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.

RELATED TAGS

java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring