Java中AbstractCollection的removeAll()方法:示例
Java.util.AbstractCollection.removeAll(Collection col)方法用于从指定集合中删除AbstractCollection中的所有元素。
语法:
AbstractCollection.removeAll(Collection col)
参数: 此方法接受一个强制参数col,它是要从AbstractCollection中删除其元素的集合。
返回值: 如果由于操作而改变了AbstractCollection,则此方法返回true,否则返回false。
异常: 如果指定的集合为空,则该方法会抛出NullPointerException异常。
以下程序说明了Java.util.AbstractCollection.removeAll(Collection col)方法:
程序1:
// Java code to illustrate removeAll()
import java.util.*;
public class AbstractCollectionDemo {
public static void main(String args[])
{
// Creating an empty AbstractCollection
AbstractCollection<String> collection
= new ArrayList<String>();
// Use add() method to add
// elements in the AbstractCollection
collection.add("Geeks");
collection.add("for");
collection.add("Geeks");
collection.add("10");
collection.add("20");
// Output the AbstractCollection
System.out.println("AbstractCollection: "
+ collection);
// Creating an empty AbstractCollection
AbstractCollection<String> colcollection
= new ArrayList<String>();
// Use add() method to add
// elements in the AbstractCollection
colcollection.add("Geeks");
colcollection.add("for");
colcollection.add("Geeks");
// Remove the head using remove()
boolean changed
= collection.removeAll(colcollection);
// Print the result
if (changed)
System.out.println("Collection removed");
else
System.out.println("Collection not removed");
// Print the final AbstractCollection
System.out.println("Final AbstractCollection: "
+ collection);
}
}
AbstractCollection: [Geeks, for, Geeks, 10, 20]
Collection removed
Final AbstractCollection: [10, 20]
程序2:
// Java代码以说明removeAll()
import java.util.*;
public class AbstractCollectionDemo {
public static void main(String args[])
{
// 创建一个空的AbstractCollection
AbstractCollection<Integer> collection
= new ArrayList<Integer>();
// 使用add()方法在AbstractCollection中添加元素
collection.add(1);
collection.add(2);
collection.add(3);
collection.add(10);
collection.add(20);
// 输出AbstractCollection
System.out.println("AbstractCollection: "
+ collection);
// 创建一个空的AbstractCollection
AbstractCollection<Integer> colcollection
= new ArrayList<Integer>();
// 使用add()方法在AbstractCollection中添加元素
colcollection.add(30);
colcollection.add(40);
colcollection.add(50);
// 使用removeAll()方法删除元素
boolean changed
= collection.removeAll(colcollection);
// 打印结果
if (changed)
System.out.println("Collection removed");
else
System.out.println("Collection not removed");
// 打印最终的AbstractCollection
System.out.println("Final AbstractCollection: "
+ collection);
}
}
AbstractCollection: [1, 2, 3, 10, 20]
Collection not removed
Final AbstractCollection: [1, 2, 3, 10, 20]