Java中的 Stack remove(Object) 方法与示例
Java.util.Stack.remove( Object o )方法用于从堆栈中删除任何特定元素。
句法:
Stack.remove(Object o)
参数:此方法接受一个强制参数o是 Stack 的对象类型,并指定要从 Stack 中删除的元素。
返回值:如果找到指定的元素并将其从堆栈中删除,则返回True ,否则返回False 。
下面的程序说明了Java.util.Stack.remove(Object o) 方法:
示例 1:
// Java code to illustrate remove() when position of
// element is passed as parameter
import java.util.*;
public class StackDemo {
public static void main(String args[])
{
// Creating an empty Stack
Stack stack = new Stack();
// Use add() method to add elements in the Stack
stack.add("Geeks");
stack.add("for");
stack.add("Geeks");
stack.add("10");
stack.add("20");
// Output the Stack
System.out.println("Stack: " + stack);
// Remove the element using remove()
boolean res = stack.remove("20");
// Print the removed element
System.out.println("Was 20 removed: "
+ res);
// Print the final Stack
System.out.println("Final Stack: "
+ stack);
}
}
输出:
Stack: [Geeks, for, Geeks, 10, 20]
Was 20 removed: true
Final Stack: [Geeks, for, Geeks, 10]
示例 2:
// Java code to illustrate remove() when position of
// element is passed as parameter
import java.util.*;
public class StackDemo {
public static void main(String args[])
{
// Creating an empty Stack
Stack stack = new Stack();
// Use add() method to add elements in the Stack
stack.add(10);
stack.add(20);
stack.add(30);
stack.add(40);
stack.add(50);
// Output the Stack
System.out.println("Stack: " + stack);
// Remove the element using remove()
boolean res = stack.remove("100");
// Print the removed element
System.out.println("Was 100 removed: "
+ res);
// Print the final Stack
System.out.println("Final Stack: "
+ stack);
}
}
输出:
Stack: [10, 20, 30, 40, 50]
Was 100 removed: false
Final Stack: [10, 20, 30, 40, 50]