Java Collections addAll()方法及实例
java.util.Collections 类的 addAll() 方法是用来将所有指定的元素添加到指定的集合中。要添加的元素可以单独指定或作为一个数组。这个方便方法的行为与c.addAll(Arrays.asList(elements))相同,但在大多数实现中,这个方法可能运行得更快。
语法
public static boolean
addAll(Collection c, T... elements)
参数: 该方法接受以下参数作为参数
- c- 要插入的元素的集合
- elements – 要插入到c中的元素
返回值: 如果集合因调用而改变,该方法返回true。
异常: 如果元素包含一个或多个空值,而c不允许空元素,或者c或元素是空的,这个方法会抛出 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<String>
List<String> arrlist = new ArrayList<String>();
// 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<String>
List<String> arrlist = new ArrayList<String>();
// 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