Java .addAll()
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.
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 ArrayListArrayList<String> list1 = new ArrayList<String>();// Add items to first ArrayListlist1.add("A");list1.add("B");list1.add("C");list1.add("D");// Create second ArrayListArrayList<String> list2 = new ArrayList<String>();// Add items to second ArrayListlist2.add("W");list2.add("X");list2.add("Y");list2.add("Z");// Print first ArrayListSystem.out.println("List 1:");System.out.println(list1);// Print second ArrayListSystem.out.println("List 2:");System.out.println(list2);// Add second ArrayList to first ArrayList at index 3list1.addAll(3, list2);// Print the combined ArrayListSystem.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]
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve 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