ArrayList.addAll(): This method is available in java.util.ArrayList class of Java.
Syntax:
boolean java.util.ArrayList.addAll(Collection<? extends E> c)
This method takes one argument. This method appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's Iterator.
Parameters: One parameter is required for this method.
c: a collection containing elements to be added to this list.
Returns: true if this list changed as a result of the call.
Throws:
1. NullPointerException - if the specified collection is null
Approach 1: When no exceptions
Java
import java.util.ArrayList;public class ArrayListAddAll {public static void main(String[] args) {ArrayList<Integer> arr = new ArrayList<>();ArrayList<Integer> arr1 = new ArrayList<Integer>();arr1.add(1);arr1.add(2);// Add all in arrarr.addAll(arr1);System.out.println("arr: ");arr.forEach((n -> System.out.print(n + " ")));System.out.println();System.out.println("arr1: ");arr1.forEach((n -> System.out.print(n + " ")));}}
Output:
arr:
1 2
arr1:
1 2
Approach 2: NullPointerException
Java
import java.util.ArrayList;public class ArrayListAddAll {public static void main(String[] args) {ArrayList<Integer> arr = new ArrayList<>();ArrayList<Integer> arr1 = null;// Add all in arrarr.addAll(arr1);System.out.println("arr: ");arr.forEach((n -> System.out.print(n + " ")));System.out.println();System.out.println("arr1: ");arr1.forEach((n -> System.out.print(n + " ")));}}
Output:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.Collection.toArray()" because "c" is null at java.base/java.util.ArrayList.addAll(ArrayList.java:670)
No comments:
Post a Comment