java removeall_Java Stack removeAll()用法及代码示例

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

用法:

Stack.removeAll(Collection col)

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

返回值:如果由于操作而改变了堆栈,则此方法返回true,否则返回False。

异常:如果指定的集合为null,则该方法引发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 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]

示例2:

// 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]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值