使用Java中的LinkedHashSet retainAll()方法的示例
java.util.LinkedHashSet类的 retainAll() 方法用于从此集合中保留包含在指定集合中的所有元素。
语法:
public boolean retainAll(Collection c)
参数: 该方法将集合c作为参数,其中包含要从此集合中保留的元素。
返回值: 该方法返回true如果此集合因调用而更改。
异常: 如果此集合包含null元素并且指定的集合不允许null元素(可选),或者指定的集合为null,则此方法将抛出NullPointerException。
以下是说明retainAll()方法的示例。
示例1:
//用于演示Integer值的retainAll()方法的Java程序
import java.util.*;
public class GFG1 {
public static void main(String[] argv) throws Exception
{
try {
// Creating object of LinkedHashSet<Integer>
LinkedHashSet<Integer>
set1 = new LinkedHashSet<Integer>();
// Populating set1
set1.add(1);
set1.add(2);
set1.add(3);
set1.add(4);
set1.add(5);
// print set1
System.out.println("LinkedHashSet before "
+ "retainAll() operation : "
+ set1);
// Creating another object of LinkedHashSet<Integer>
LinkedHashSet<Integer>
set2 = new LinkedHashSet<Integer>();
set2.add(1);
set2.add(2);
set2.add(3);
// print set2
System.out.println("Collection Elements"
+ " to be retained : "
+ set2);
// Removing elements from set
// specified in set2
// using retainAll() method
set1.retainAll(set2);
// print set1
System.out.println("LinkedHashSet after "
+ "retainAll() operation : "
+ set1);
}
catch (NullPointerException e) {
System.out.println("Exception thrown : " + e);
}
}
}
LinkedHashSet before retainAll() operation : [1, 2, 3, 4, 5]
Collection Elements to be retained : [1, 2, 3]
LinkedHashSet 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 {
// 创建LinkedHashSet<Integer>对象
LinkedHashSet<Integer>
set1 = new LinkedHashSet<Integer>();
// 填充集合set1
set1.add(1);
set1.add(2);
set1.add(3);
set1.add(4);
set1.add(5);
// 输出set1
System.out.println("LinkedHashSet在执行retainAll()操作之前:"
+ set1);
// 创建另一个LinkedHashSet<Integer>对象
LinkedHashSet<Integer>
set2 = null;
// 输出set2
System.out.println("要保留的集合元素为:"
+ set2);
System.out.println("\n尝试将null作为指定元素传递\n");
// 用retainAll()方法从set2指定的set1中删除元素
set1.retainAll(set2);
// 输出set1
System.out.println("LinkedHashSet 在执行retainAll()操作之后: "
+ set1);
}
catch (NullPointerException e) {
System.out.println("抛出异常: " + e);
}
}
}
LinkedHashSet在执行retainAll()操作之前:[1, 2, 3, 4, 5]
要保留的集合元素为:null
尝试将null作为指定元素传递
抛出异常: java.lang.NullPointerException
极客教程