ArrayList addAll(Collection c) method in java

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

ArrayList addAll(Collection c) method in java

ArrayList addAll(Collection<? extends E> c) method in java 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:

c collection containing elements to be added to this list.

Returns:

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

Throws:

NullPointerException – if the specified collection is null.

Also read – ArrayList in java

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

import java.util.ArrayList;
public class ArrayListAddAllMethodExample
{
   public static void main(String[] args)
   {
      // creating an empty array ArrayList with an initial capacity
      ArrayList<Integer> al1 = new ArrayList<Integer>(5);
      al1.add(12);
      al1.add(14);
      al1.add(16);
      // printing all ArrayList elements
      System.out.println("ArrayList 1: ");
      for(Integer number : al1)
      {
         System.out.println("Number: " + number);
      }
      // creating another empty ArrayList with an initial capacity
      ArrayList<Integer> al2 = new ArrayList<Integer>(5);
      al2.add(19);
      al2.add(21);
      al2.add(23);
      al2.add(25);
      // printing all the elements of second ArrayList
      System.out.println("ArrayList 2: ");
      for(Integer number : al2)
      {
         System.out.println("Number: " + number);
      }
      // inserting all elements
      al1.addAll(al2);
      System.out.println("Printing all ArrayList elements: ");
      // let us print all the elements available in list1
      for(Integer number : al1)
      {
         System.out.println("Number: " + number);
      }
   }
}


Output:

ArrayList 1:
Number: 12
Number: 14
Number: 16
ArrayList 2:
Number: 19
Number: 21
Number: 23
Number: 25
Printing all ArrayList elements:
Number: 12
Number: 14
Number: 16
Number: 19
Number: 21
Number: 23
Number: 25