Java.util.ArrayList.addAll(Collection c) Method Example

The addAll(Collection c) method of java.util.ArrayList class will simply inserts all of the elements in the specified collection to the end of this list.

Signature

public boolean addAll(Collection c)

This method appends all the elements of a collection at the end of the list and will throw “NullPointerException” when the specified collection is null.

Example

The following example shows the usage of Arraylist.addAll(c) method.

import java.util.ArrayList;

public class ArrayListAddAll 
{
	public static void main(String[] args) { 
        // Create ArrayList al1 object
        ArrayList al1 = new ArrayList();
        
        //adding elements to al1
        al1.add("String 1");
        al1.add("String 2");
        al1.add("String 3");
        al1.add("String 4");
        
        System.out.println("**Elements of al1 before adding**");
        for(String val: al1)
        {
        	System.out.println(val);
        }

        // Create ArrayList al2 object
        ArrayList al2 = new ArrayList();
        
        //adding elements to al2
        al2.add("Element 1");
        al2.add("Element 2");
        al2.add("Element 3");
        al2.add("Element 4");

        //Adding al2 to al1
        al1.addAll(al2);

        System.out.println("**Elements of al1 after adding**");
        for(String val: al1)
        {
        	System.out.println(val);
        }
   }
}

Output

**Elements of al1 before adding**
String 1
String 2
String 3
String 4
**Elements of al1 after adding**
String 1
String 2
String 3
String 4
Element 1
Element 2
Element 3
Element 4

Leave a Reply

Your email address will not be published. Required fields are marked *