Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What is the Stack.remove(Object) 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

The Stack class in Java is an implementation of Last-In-First-Out (LIFO)The element inserted first is processed last and the element inserted last is processed first. behavior.

The Remove method

The remove method of the Stack class can be used to remove the first occurrence of a specific element from the stack. The elements after the index will be shifted one index downward. The size of the stack also decreases by 1.

Syntax

public boolean remove(Object obj)

Argument

The method takes the element to be removed from the stack object as an argument.

Return value

remove returns true if the passed argument is present in the stack. Otherwise, the method returns false.

Code

import java.util.Stack;
class remove {
public static void main( String args[] ) {
// Creating Stack
Stack<String> stack = new Stack<>();
// add elememts
stack.add("hi");
stack.add("hello");
stack.add("hi");
System.out.println("The Stack is: " + stack);
stack.remove("hi");
System.out.println("\nAfter removing element 'hi'. The Stack is: " + stack);
}
}

Please click the Run button on the code section above to see how the remove method works.

Explanation

In the code above:

  • Line 5: We create a stack object.

  • Lines 8-10: We add three elements (hi, hello, hi) to the created stack object.

  • Line 14: We use the remove method of the stack object to remove the element hi. The element hi is present at index 0 and 2. The remove method will delete the first occurrence of hi, so hi at index 0 is deleted.

If the element type of the Stack is Integer, then using the remove(object) method will result in removing the element at the passed integer index. To handle this case, use the removeElement method of the stack object.

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