// Java program to illustrate retainAll() method
import java.util.*;
public class AbstractCollectionDemo {
public static void main(String[] args)
{
// Creating an arraylist
AbstractCollection
输出:
Set 1 contains:
[one, two, three]
Set 2 contains:
[three, one, five]
Set 2 after invoking retainAll() method:
[three, one]
程序 2:显示 NullPointerException
// Java program to illustrate retainAll() method
import java.util.*;
public class NullPointerExample {
public static void main(String[] args)
{
// Creating an arraylist
// and assigning null to it
AbstractCollection set1 = null;
// creating another arraylist
AbstractCollection set2
= new ArrayList();
// adding values in set 2 list
set2.add("one");
set2.add("two");
set2.add("three");
// before invoking retainAll()
System.out.println("Set 1 contains:"
+ set1 + "\n");
System.out.println("Set 2 contains:"
+ set2 + "\n");
try {
// invoking retainAll()
set2.retainAll(set1);
// after invoking retainAll()
System.out.println("Set 2 after invoking "
+ "retainAll() method:\n"
+ set2);
}
catch (Exception e) {
System.out.println(e);
}
}
}
输出:
Set 1 contains:null
Set 2 contains:[one, two, three]
java.lang.NullPointerException