How to insert all the Collection Elements at Specified position in ArrayList

In the last tutorial I have shared an example of addAll(Collection c) method which is used for adding all the elements of Collection c at the end of the list. In this tutorial we will see another variant of addAll(int index, Collection c) method.Syntax of the method is :

public boolean addAll(int index, Collection c)

According to Oracle docs, this method inserts all of the elements in the specified collection into the ArrayList, starting at the specified position.

addAll(int index, Collection c) example


import java.util.*;
public class AddAllMethodExample {
    public static void main(String args[]) {
        

       // ArrayList1 
       ArrayList<String> al = new ArrayList<String>();
       al.add("Apple");
       al.add("Orange");
       al.add("Grapes");
       al.add("Mango");
       System.out.println("ArrayList1 before addAll:"+al);
       //ArrayList2 
       ArrayList<String> al2 = new ArrayList<String>();
       al2.add("Blackberry");
       al2.add("Strawberry");
       al2.add("Banana");
       al2.add("Guava");
       System.out.println("ArrayList2 content:"+al2);

       //Adding ArrayList2 in ArrayList1 at 4th position(index =3)
       al.addAll(3, al2);
       System.out.println("ArrayList1 after adding ArrayList2 at 4th Pos:\n"+al);


    }
}


Output

ArrayList1 before addAll:[Apple, Orange, Grapes, Mango]
ArrayList2 content:[Blackberry, Strawberry, Banana, Guava]
ArrayList1 after adding ArrayList2 at 4th Pos:
[Apple, Orange, Grapes, Blackberry, Strawberry, Banana, Guava, Mango]



About The Author

Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry