📌  相关文章
📜  Java中的堆栈 removeAll() 方法与示例

📅  最后修改于: 2022-05-13 01:55:38.740000             🧑  作者: Mango

Java中的堆栈 removeAll() 方法与示例

Java.util.Stack.removeAll(Collection col)方法用于从堆栈中删除指定集合中存在的所有元素。

句法:

Stack.removeAll(Collection col)

参数:此方法接受一个强制参数col ,该参数是要从堆栈中删除其元素的集合。

返回值:如果堆栈由于操作而发生更改,则此方法返回true ,否则返回False

异常:如果指定的集合为空,该方法将抛出NullPointerException

下面的程序说明了Java.util.Stack.removeAll(Collection col) 方法:

方案一:

// Java code to illustrate removeAll()
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);
  
        // Creating an empty Stack
        Stack colstack = new Stack();
  
        // Use add() method to add elements in the Stack
        colstack.add("Geeks");
        colstack.add("for");
        colstack.add("Geeks");
  
        // Remove the head using remove()
        boolean changed = stack.removeAll(colstack);
  
        // Print the result
        if (changed)
            System.out.println("Collection removed");
        else
            System.out.println("Collection not removed");
  
        // Print the final Stack
        System.out.println("Final Stack: " + stack);
    }
}
输出:
Stack: [Geeks, for, Geeks, 10, 20]
Collection removed
Final Stack: [10, 20]

方案二:

// Java code to illustrate removeAll()
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(1);
        stack.add(2);
        stack.add(3);
        stack.add(10);
        stack.add(20);
  
        // Output the Stack
        System.out.println("Stack: " + stack);
  
        // Creating an empty Stack
        Stack colstack = new Stack();
  
        // Use add() method to add elements in the Stack
        colstack.add(30);
        colstack.add(40);
        colstack.add(50);
  
        // Remove the head using remove()
        boolean changed = stack.removeAll(colstack);
  
        // Print the result
        if (changed)
            System.out.println("Collection removed");
        else
            System.out.println("Collection not removed");
  
        // Print the final Stack
        System.out.println("Final Stack: " + stack);
    }
}
输出:
Stack: [1, 2, 3, 10, 20]
Collection not removed
Final Stack: [1, 2, 3, 10, 20]