java.util.Collections类的addAll()方法用于将所有指定的元素添加到指定的集合中。要添加的元素可以单独指定或作为数组指定。此便捷方法的行为与c.addAll(Arrays.asList(elements))的行为相同,但是在大多数实现下,此方法的运行速度可能明显更快。
用法:
public static boolean
addAll(Collection c, T... elements)
参数:此方法将以下参数作为参数
c-要插入元素的集合
elements-要插入c的元素
返回值:如果集合由于调用而发生更改,则此方法返回true。
异常:如果元素包含一个或多个null值并且c不允许为null元素,或者c或元素为null,则此方法引发NullPointerException
以下示例说明了addAll()方法
示例1:
// Java program to demonstrate
// addAll() method
import java.util.*;
public class GFG1 {
public static void main(String[] argv) throws Exception
{
try {
// creating object of List
List arrlist = new ArrayList();
// Adding element to arrlist
arrlist.add("A");
arrlist.add("B");
arrlist.add("C");
arrlist.add("Tajmahal");
// printing the arrlist before operation
System.out.println("arrlist before operation : " + arrlist);
// add the specified element to specified Collections
// using addAll() method
boolean b = Collections.addAll(arrlist, "1", "2", "3");
// printing the arrlist after operation
System.out.println("result : " + b);
// printing the arrlist after operation
System.out.println("arrlist after operation : " + arrlist);
}
catch (NullPointerException e) {
System.out.println("Exception thrown : " + e);
}
catch (IllegalArgumentException e) {
System.out.println("Exception thrown : " + e);
}
}
}
输出:
arrlist before operation : [A, B, C, Tajmahal]
result : true
arrlist after operation : [A, B, C, Tajmahal, 1, 2, 3]
输出:
arrlist before operation : [A, B, C, Tajmahal]
result : true
arrlist after operation : [A, B, C, Tajmahal, 1, 2, 3]
示例2:对于NullPointerException
// Java program to demonstrate
// addAll() method
import java.util.*;
public class GFG1 {
public static void main(String[] argv) throws Exception
{
try {
// creating object of List
List arrlist = new ArrayList();
// Adding element to arrlist
arrlist.add("A");
arrlist.add("B");
arrlist.add("C");
arrlist.add("Tajmahal");
// printing the arrlist before operation
System.out.println("arrlist before operation : " + arrlist);
// add the specified element to specified Collections
// using addAll() method
System.out.println("\nTrying to add the null value with arrlist");
boolean b = Collections.addAll(null, arrlist);
// printing the arrlist after operation
System.out.println("result : " + b);
// printing the arrlist after operation
System.out.println("arrlist after operation : " + arrlist);
}
catch (NullPointerException e) {
System.out.println("Exception thrown : " + e);
}
catch (IllegalArgumentException e) {
System.out.println("Exception thrown : " + e);
}
}
}
输出:
arrlist before operation : [A, B, C, Tajmahal]
Trying to add the null value with arrlist
Exception thrown : java.lang.NullPointerException