Java Stack remove(Object)方法与实例

Java Stack remove(Object)方法与实例

Java.util.Stack.remove( Object o )方法用于从Stack中删除任何特定元素。

语法

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<String> stack = new Stack<String>();
  
        // 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<Integer> stack = new Stack<Integer>();
  
        // 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]

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程