ArrayList addAll(int index Collection c) method in java

Let’s learn ArrayList addAll(int index, Collection c) method in java.

ArrayList addAll(int index, Collection <? extends E>c) method in java

addAll(int index, Collection <? extends E>c) method of ArrayList class inserts all of the elements in the specified collection into this list, starting at the specified position.

Syntax:

public boolean addAll(int index, Collection<? extends E> c)

Parameters:

index index at which to insert the first element from thespecified collection.

c collection containing elements to be added to this list.

Returns:

true if this list changed as a result of the call.

Throws:

IndexOutOfBoundsException – if the index is out of range(index < 0 || index > size()).

NullPointerException – if the specified collection is null.

Now let’s see an example on ArrayList addAll(int index, Collection <? extends E>c) method.

import java.util.ArrayList;
public class ArrayListAddAllMethod
{
   public static void main(String[] args)
   {
      // creating an empty ArrayList with initial capacity
      ArrayList<Integer> al1 = new ArrayList<Integer>(5);
      al1.add(11);
      al1.add(13);
      al1.add(15);
      // printing all elements of al1
      System.out.println("ArrayList 1 elements: ");
      for(Integer number : al1)
      {
         System.out.println("Number: " + number);
      }
      // creating another empty ArrayList with initial capacity
      ArrayList<Integer> al2 = new ArrayList<Integer>(5);
      al2.add(12);
      al2.add(14);
      al2.add(16);
      al2.add(18);
      // printing all elements of ArrayList2
      System.out.println("ArrayList 2 elements: ");
      for(Integer number : al2)
      {
         System.out.println("Number: " + number);
      }
      // insert all elements of al2 at third position
      al1.addAll(2, al2);
      System.out.println("Print all elements: ");
      // printing all elements in al1
      for(Integer number : al1)
      {
         System.out.println("Number: " + number);
      }
   }
}

Output:

ArrayList 1 elements:
Number: 11
Number: 13
Number: 15
ArrayList 2 elements:
Number: 12
Number: 14
Number: 16
Number: 18
Print all elements:
Number: 11
Number: 13
Number: 12
Number: 14
Number: 16
Number: 18
Number: 15