What is the Stack.remove(Object) method in Java?
The Stack class
The Stack class in Java is an implementation of
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 StackStack<String> stack = new Stack<>();// add elememtsstack.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
Runbutton on the code section above to see how theremovemethod works.
Explanation
In the code above:
-
Line 5: We create a
stackobject. -
Lines 8-10: We add three elements (
hi, hello, hi) to the createdstackobject. -
Line 14: We use the
removemethod of thestackobject to remove the elementhi. The elementhiis present at index0and2. Theremovemethod will delete the first occurrence ofhi, sohiat index0is deleted.
If the element type of the
StackisInteger, then using theremove(object)method will result in removing the element at the passed integer index. To handle this case, use theremoveElementmethod of thestackobject.