Java Stack removeAll()方法及示例
Java.util.Stack .removeAll(Collection col)方法用于从Stack中删除指定集合中的所有元素。
语法
Stack.removeAll(Collection col)
参数: 该方法接受一个强制参数col,它是一个集合,其元素将被从Stack中删除。
返回值: 如果堆栈由于操作而被改变,该方法返回 true ,否则返回 False。
异常: 如果指定的集合为空,该方法会抛出NullPointerException。
下面的程序说明了Java.util.Stack.removeAll(Collection col)方法。
程序1 :
// Java code to illustrate removeAll()
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);
// Creating an empty Stack
Stack<String> colstack = new Stack<String>();
// 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]
示例2
// Java code to illustrate removeAll()
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(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<Integer> colstack = new Stack<Integer>();
// 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]
极客教程