Java ArrayList addall() Method with Example (original) (raw)

Last Updated : 10 Dec, 2024

The **addAll() method in the ArrayList class is used to **add all the elements from a specified collection into an ArrayList. This method is especially useful for combining collections or inserting multiple elements at once.

**Example: Here, we will add elements to the end of the list.

Java `

// Java program to demonstrate // adding all elements to the end of a list import java.util.ArrayList; public class GFG {

public static void main(String[] args) {
  
    // Creating an ArrayList and 
    // adding initial elements
    ArrayList<String> l1 = new ArrayList<>();
    l1.add("Java");
    l1.add("C++");

    // Creating another ArrayList 
    // with elements to be added
    ArrayList<String> l2 = new ArrayList<>();
    l2.add("C");

    // Adding all elements 
    // from l2 to l1
    l1.addAll(l2);
    System.out.println("" + l1);
}

}

`

**Now, there are two versions of the ArrayList addAll() method, i.e., one that appends elements at the end of the list and another that inserts elements at a specified position in the list.

1. boolean addAll(Collection c)

This version appends all elements of the specified collection to the end of the ArrayList.

**Syntax:

boolean addAll(Collection c)

**Implementation:

Java `

// Java program to demonstrate // adding all elements at the end of ArrayList import java.util.ArrayList;

public class GFG { public static void main(String[] args) {

    ArrayList<Integer> l1 = new ArrayList<>();
    l1.add(10);
    l1.add(20);

    ArrayList<Integer> l2 = new ArrayList<>();
    l2.add(30);
    l2.add(40);

    // Adding all elements from 
    // l2 to l1
    l1.addAll(l2);

    System.out.println("Final ArrayList: " + l1);
}

}

`

Output

Final ArrayList: [10, 20, 30, 40]

2. boolean addAll(int index, Collection c)

This version inserts all elements from the specified collection into the ArrayList at the specified index. It shifts the current elements and subsequent elements to the right.

**Syntax:

boolean addAll(int index, Collection c)

**Parameters:

// Java program to demonstrate adding // elements at a specific index import java.util.ArrayList;

public class GFG {

public static void main(String[] args) {
  
    ArrayList<String> l1 = new ArrayList<>();
    l1.add("Java");
    l1.add("C++");
    l1.add("Python");

    ArrayList<String> l2 = new ArrayList<>();
    l2.add("C");
    l2.add("AI");

    // Adding elements of 
    // l2 at index 2
    l1.addAll(2, l2);

    System.out.println("" + l1);
}

}

`

Output

[Java, C++, C, AI, Python]