Java中的堆栈retainAll()方法示例
java.util.Stack 类的 retainAll() 方法用于从此堆栈中保留包含在指定集合中的所有元素。
语法:
public boolean retainAll(Collection c)
参数: 将要从此堆栈中保留的元素包含在参数集合c中。
返回值: 该方法返回true,如果这个堆栈因为此调用的原因而改变。
异常: 如果此堆栈包含空元素,并且指定的集合不允许空元素(可选),或者指定的集合为null,则此方法会抛出 NullPointerException 。
以下是说明retainAll()方法的示例。
示例1:
// Java程序演示
// Integer值的retainAll()方法
import java.util.*;
public class GFG1 {
public static void main(String[] argv) throws Exception {
try {
//创建 Stack 对象
Stack stack1 = new Stack ();
//填充 stack1
stack1.add(1);
stack1.add(2);
stack1.add(3);
stack1.add(4);
stack1.add(5);
// 打印 stack1
System.out.println("Stack before "
+ "retainAll() operation : "
+ stack1);
// 创建 Stack 的另一个对象
Stack stack2 = new Stack ();
stack2.add(1);
stack2.add(2);
stack2.add(3);
// 打印 stack2
System.out.println("Collection Elements"
+ " to be retained : "
+ stack2);
// 使用 retainAll()方法
// 从 stack1 中删除在 stack2 中指定的元素
stack1.retainAll(stack2);
// 打印 stack1
System.out.println("Stack after "
+ "retainAll() operation : "
+ stack1);
}
catch (NullPointerException e) {
System.out.println("Exception thrown : " + e);
}
}
}
Stack before retainAll() operation : [1, 2, 3, 4, 5]
Collection Elements to be retained : [1, 2, 3]
Stack after retainAll() operation : [1, 2, 3]
示例2: NullPointerException 异常
// Java程序演示
// retainAll()方法用于整数类型的值
import java.util.*;
public class GFG1 {
public static void main(String[] argv) throws Exception
{
try {
// 创建Stack<Integer>对象
Stack<Integer>
stack1 = new Stack<Integer>();
// 填充stack1
stack1.add(1);
stack1.add(2);
stack1.add(3);
stack1.add(4);
stack1.add(5);
// 打印stack1
System.out.println("Stack before "
+ "retainAll() operation : "
+ stack1);
// 创建Stack<Integer>的另一个对象
Stack<Integer>
stack2 = null;
// 打印stack2
System.out.println("Collection Elements"
+ " to be retained : "
+ stack2);
System.out.println("\nTrying to pass "
+ "null as a specified element\n");
// 使用retainAll()方法从stack1中删除stack2中指定的元素
stack1.retainAll(stack2);
// 打印stack1
System.out.println("Stack after "
+ "retainAll() operation : "
+ stack1);
}
catch (NullPointerException e) {
System.out.println("Exception thrown : " + e);
}
}
}
在使用retainAll()方法之前的Stack: [1, 2, 3, 4, 5]
Collection Elements to be retained : null
尝试将null作为指定元素传递时
发生的异常:java.lang.NullPointerException