Stack
classThe Stack
class in Java is an implementation of
Remove
methodThe 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
.
public boolean remove(Object obj)
The method takes the element to be removed from the stack
object as an argument.
remove
returns true
if the passed argument is present in the stack
. Otherwise, the method returns false
.
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
Run
button on the code section above to see how theremove
method works.
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
isInteger
, then using theremove(object)
method will result in removing the element at the passed integer index. To handle this case, use theremoveElement
method of thestack
object.