Java .addAll()

StevenSwiniarski's avatar
Published Jun 16, 2022Updated Oct 17, 2022
Contribute to Docs

The .addAll() method is used to add the contents of a collection to an instance of the ArrayList class.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
    • Beginner Friendly.
      17 hours

Syntax

arrayListInstance.addAll(index, collection);

The contents of collection are inserted into the arrayListInstance at the specified index. The collection must be of the same data type as arrayListInstance.

Example

The following example creates two ArrayLists and inserts one into the other.

import java.util.ArrayList;
public class testAddAll {
public static void main(String[] args) {
// Create first ArrayList
ArrayList<String> list1 = new ArrayList<String>();
// Add items to first ArrayList
list1.add("A");
list1.add("B");
list1.add("C");
list1.add("D");
// Create second ArrayList
ArrayList<String> list2 = new ArrayList<String>();
// Add items to second ArrayList
list2.add("W");
list2.add("X");
list2.add("Y");
list2.add("Z");
// Print first ArrayList
System.out.println("List 1:");
System.out.println(list1);
// Print second ArrayList
System.out.println("List 2:");
System.out.println(list2);
// Add second ArrayList to first ArrayList at index 3
list1.addAll(3, list2);
// Print the combined ArrayList
System.out.println("List 1 + List 2:");
System.out.println(list1);
}
}

The output would look like this:

List 1:
[A, B, C, D]
List 2:
[W, X, Y, Z]
List 1 + List 2:
[A, B, C, W, X, Y, Z, D]

All contributors

Contribute to Docs

Learn Java on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
    • Beginner Friendly.
      17 hours