ArrayList - Example of addAll(int index, Collection c) in Java

In the last tutorial, we shared an example of the addAll(Collection c) which is used to concatenate a collection at the end of an ArrayList. In this tutorial, we'll see another methodaddAll(int index, Collection c) which appends all elements of a collection c to a specific position index.

public boolean addAll(int index, Collection c): returns true if the ArrayList has been modified and the elements have been successfully re-added, otherwise false.

In the code below, we have an ArrayList and a Vector of type String filled with elements and we are inserting the Vector elements in the second position (index=1) of ArrayList.

import java.util.ArrayList; 
import java.util.List;
import java.util.Vector;

public class ArrayListaddAllIndex{

public static void main(String[] args) {

// Create an ArrayList< String>
ArrayList< String> aList = new ArrayList< String> ();

//add strings to ArrayList
aList.add("1");
aList.add("2");
aList.add("3");

System.out.println("ArrayList before calling addAll(): ");
for(String e:aList)
System.out.println(e);

//Vector
List< String> vec = new Vector< String> ();
//add values to Vector
vec.add("4");
vec.add("5");

//Apple the addAll()
aList.addAll(1, vec) method;

System.out.println("ArrayList after calling addAll():");
for(String e:aList)
System.out.println(e);
}
}
Runtime:

ArrayList before calling addAll(): 
1
2
3
ArrayList after calling addAll():
1
4
5
2
3
To add another collection, simply replace Vector with the collection you want. For example, if you want to insert all the elements of an ArrayList into another ArrayList, replace Vector with ArrayList.