Java ConcurrentSkipListSet removeAll()方法
java.util.concurrent.ConcurrentSkipListSet 的 removeAll() 方法是Java中的一个内置函数,它返回从这个集合中删除所有包含在指定集合中的元素。如果指定的集合也是一个集合,这个操作可以有效地修改这个集合,使其值为两个集合的不对称集合差。
语法
public boolean removeAll(Collection c)
参数: 该函数接受一个单一的参数c
返回值: 如果该集合因调用而发生变化,则该函数返回真。
异常: 该函数会抛出下列异常。
- ClassCastException - 如果这个集合中的一个或多个元素的类型与指定的集合不兼容。
- NullPointerException - 如果指定的集合或其任何元素为空。
下面的程序说明了ConcurrentSkipListSet.removeAll()方法。
程序1 :
// Java program to demonstrate removeAll()
// method of ConcurrentSkipListSet
import java.util.concurrent.*;
import java.util.ArrayList;
import java.util.List;
class ConcurrentSkipListSetremoveAllExample1 {
public static void main(String[] args)
{
// Initializing the List
List<Integer> list = new ArrayList<Integer>();
// Adding elements in the list
for (int i = 1; i <= 10; i += 2)
list.add(i);
// Contents of the list
System.out.println("Contents of the list: " + list);
// Initializing the set
ConcurrentSkipListSet<Integer>
set = new ConcurrentSkipListSet<Integer>();
// Adding elements in the set
for (int i = 1; i <= 10; i++)
set.add(i);
// Contents of the set
System.out.println("Contents of the set: " + set);
// Remove all elements from the set which are in the list
set.removeAll(list);
// Contents of the set after removal
System.out.println("Contents of the set after removal: "
+ set);
}
}
输出。
Contents of the list: [1, 3, 5, 7, 9]
Contents of the set: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Contents of the set after removal: [2, 4, 6, 8, 10]
程序2: 在removeAll()中显示NullPOinterException的程序。
// Java program to demonstrate removeAll()
// method of ConcurrentSkipListSet
import java.util.concurrent.*;
import java.util.ArrayList;
import java.util.List;
class ConcurrentSkipListSetremoveAllExample1 {
public static void main(String[] args)
{
// Initializing the set
ConcurrentSkipListSet<Integer>
set = new ConcurrentSkipListSet<Integer>();
// Adding elements in the set
for (int i = 1; i <= 10; i++)
set.add(i);
// Contents of the set
System.out.println("Contents of the set: " + set);
try {
// Remove all elements from the set which are null
set.removeAll(null);
}
catch (Exception e) {
System.out.println("Exception: " + e);
}
}
}
输出。
Contents of the set: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Exception: java.lang.NullPointerException
参考资料
https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentSkipListSet.html#removeAll-java.util.Collection-