In Java, removeElement(obj)removes the first occurrence of obj from a Stack, searching upward from the bottom with equals(). Elements above it move down one place, and the method returns true if something was removed.
It is the legacy Vector name behind remove(Object), which simply calls it. Because the search starts at the bottom, it removes the oldest copy of a repeated value, not the copy nearest the top that search() would report.
An instance method inherited from java.util.Vector (since Java 1.0). Stack does not override it: index 0 is the bottom of the stack and index size() - 1 is the top.
Syntax
Pass the value to remove.
Java
Stack<String> stack = new Stack<>();
stack.push("x");
stack.push("y");
stack.push("x"); // [x, y, x]
boolean a = stack.removeElement("x"); // true, [y, x] (the bottom x went)
boolean b = stack.removeElement("z"); // false, unchanged
Call
What it does
stack.removeElement(o)
Removes the first match from the bottom; true or false.
while (stack.removeElement(o)) { }
Removes every copy of o.
stack.remove(o)
The List name; it calls removeElement.
stack.removeElementAt(stack.lastIndexOf(o))
Removes the copy nearest the top instead (check for -1 first).
removeElement scans from the bottom and then shifts the elements above the match, so its cost grows with the stack size.
Library declarations
Java
// java.util.Vector<E>, inherited by Stack<E>
public synchronized boolean removeElement(Object obj)
Parameters
Parameter
Description
obj (Object)
The value to remove, compared with equals(); null removes the first null element.
Return Value
Return Value
Description
boolean
true if a matching element was removed, false if none was found.