Java中的CopyOnWriteArrayList removeAll()方法及示例
CopyOnWriteArrayList类中的removeAll()方法可以从调用对象的CopyOnArrayList中删除指定集合中包含的所有元素。
语法:
public boolean removeAll(Collection collection)
参数:该方法仅接受一个参数collection,即要从调用对象中删除的集合。
返回值:该方法返回一个布尔值。如果此删除操作成功,则返回true。
异常:该方法会抛出以下异常:
- ClassCastException:如果此列表元素的类与指定的集合不兼容。
- NullPointerException: 如果指定的集合为null,或者如果此列表包含空元素且指定的集合不允许空元素。
以下示例说明了removeAll()方法:
示例1:
// Java program to demonstrate removeAll() method
import java.util.ArrayList;
import java.util.concurrent.CopyOnWriteArrayList;
public class Demo {
public static void main(String args[])
{
// Get the CopyOnWriteArrayList
CopyOnWriteArrayList<String> wishlist
= new CopyOnWriteArrayList<>();
// Add the elements in the CopyOnWriteArrayList
wishlist.add("TV");
wishlist.add("computer");
wishlist.add("play station");
wishlist.add("mobile");
wishlist.add("smart watch");
// Print the CopyOnWriteArrayList
System.out.println("CopyOnWriteArrayList: \n"
+ wishlist);
// Get the collection to be removed
ArrayList<String> checkList
= new ArrayList<>();
checkList.add("play station");
checkList.add("TV");
checkList.add("mobile");
System.out.println("\nCollection to be removed:\n"
+ checkList);
// Remove the collection from CopyOnWriteArrayList
// using removeAll() method
wishlist.removeAll(checkList);
// Print the CopyOnWriteArrayList after removal
System.out.println("\nAfter removal of collection"
+ " from CopyOnWriteArrayList:\n"
+ wishlist);
}
}
CopyOnWriteArrayList:
[TV, computer, play station, mobile, smart watch]
Collection to be removed:
[play station, TV, mobile]
After removal of collection from CopyOnWriteArrayList:
[computer, smart watch]
示例2:演示NullPointerException
// 展示 removeAll() 方法的 Java 程序
import java.util.ArrayList;
import java.util.concurrent.CopyOnWriteArrayList;
public class Demo {
public static void main(String args[])
{
// 获取 CopyOnWriteArrayList
CopyOnWriteArrayList<String> wishlist
= new CopyOnWriteArrayList<>();
// 向 CopyOnWriteArrayList 添加元素
wishlist.add("电视");
wishlist.add("电脑");
wishlist.add("PlayStation 游戏机");
wishlist.add("手机");
wishlist.add("智能手表");
// 输出 CopyOnWriteArrayList
System.out.println("CopyOnWriteArrayList: \n"
+ wishlist);
// 获取要移除的集合
ArrayList<String> checkList
= null;
System.out.println("\n要移除的集合:"
+ checkList);
try {
// 使用 removeAll() 方法从 CopyOnWriteArrayList 移除集合
wishlist.removeAll(checkList);
}
catch (Exception e) {
// 输出 Exception
System.out.println("\n从 CopyOnWriteArrayList 移除 null "
+ "时出现异常:\n"
+ e);
}
}
}
CopyOnWriteArrayList:
[电视, 电脑, PlayStation 游戏机, 手机, 智能手表]
要移除的集合:null
从 CopyOnWriteArrayList 移除 null 时出现异常:
java.lang.NullPointerException
极客教程