Java ArrayList addAll(int index,Collection C) Method Example

The addAll(int index,Collection c) method of java.util.ArrayList class will inserts all the element of the collection from the position mentioned as index

Signature

public boolean addAll(int index,Collection c)

Inserts all of the elements in the specified collection into this list, starting at the specified position and will throw “NullPointerException” when the specified collection is null and IndexOutOfBoundsException when the index is out of range.

Example

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

import java.util.ArrayList;

public class ArrayListAddAllIndexExample
{
	public static void main(String[] args) { 
        // Create ArrayList al1 object
        ArrayList al1 = new ArrayList();
        
        //adding elements to al1
        al1.add("Element1");
        al1.add("Element2");
        al1.add("Element3");
        al1.add("Element4");
        
       //printing all the values of the ArrayList
        System.out.println("**Contents of List 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("String1");
        al2.add("String2");
        al2.add("String3");
        al2.add("String4");
                
        //Adding element of al2 to al1 at index 2
        al1.addAll(2,al2);
        
        System.out.println("**Contents of List al1 after adding**");
        for(String val: al1)
        {
        	System.out.println(val);
        }

   }
}

Output

**Contents of List al1 before adding**
Element1
Element2
Element3
Element4
**Contents of List al1 after adding**
Element1
Element2
String1
String2
String3
String4
Element3
Element4

Leave a Reply

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