ArrayList.addAll(): This method is available in java.util.ArrayList class of Java.
Syntax:
boolean java.util.ArrayList.addAll(int index, Collection<? extends Integer> c)
This method takes two arguments as its parameters. This method inserts all of the elements in the specified collection into this list, starting at the specified position.
Parameters: Two parameters are required for this method.
index: index at which to insert the first element from the specified collection.
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. IndexOutOfBoundsException - if the index is out of range(index < 0 || index > size()).
2. NullPointerException - if the specified collection is null
Approach 1: When no exceptions
Java
import java.util.ArrayList;public class ArrayListAddAllAtIndex {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.add(5);arr.add(4);arr.add(6);arr.addAll(1, arr1);arr.forEach((n -> System.out.print(n + " ")));}}
Output:
5 1 2 4 6
Approach 2: IndexOutOfBoundsException
Java
import java.util.ArrayList;public class ArrayListAddAllAtIndex {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.add(5);arr.add(4);arr.add(6);arr.addAll(8, arr1);arr.forEach((n -> System.out.print(n + " ")));}}
Output:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 8, Size: 3 at java.base/java.util.ArrayList.rangeCheckForAdd(ArrayList.java:756) at java.base/java.util.ArrayList.addAll(ArrayList.java:700)
Approach 3: NullPointerException
Java
import java.util.ArrayList;public class ArrayListAddAllAtIndex {public static void main(String[] args) {ArrayList<Integer> arr = new ArrayList<>();ArrayList<Integer> arr1 = null;// Add all in arrarr.add(5);arr.add(4);arr.add(6);arr.addAll(1, arr1);arr.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:702) at com.example.ArrayList.ArrayListAddAllAtIndex.main(ArrayListAddAllAtIndex.java:13)
No comments:
Post a Comment