What is the addAll() method in Java?
The main function of the addAll() method in Java is to add elements into a Java collection. There are two addAll() methods in Java:
- The static method in the Collections class.
- The instance method in the Collection interface.
Return value
The addAll() method returns true if the collection changes as a result of elements being added into it; otherwise, it will return false.
1. Collections.addAll()
Parameters
- The collection in which elements are to be added.
- The list of the elements to be added, these elements can be in the form of an array, ​or they can be specified.
Code
import java.util.ArrayList;import java.util.Collections;import java.util.HashSet;public class AddAll {public static void main(String[] args) {// Declaring a list and adding elements:ArrayList<Integer> arr = new ArrayList<>();arr.add(10);arr.add(20);arr.add(30);// Adding a whole array:Integer[] arr2 = {new Integer(40), new Integer(50)};Collections.addAll(arr, arr2);// Adding specified elements:Collections.addAll(arr, 60, 70, 80);// Printing elementsarr.forEach(System.out::println);}}
2. The instance method addAll()
This method is defined only in the classes that implement the Collection interface (e.g., ArrayList, HashSet, etc.).
Parameter
- The index of the caller array at which the elements are to be inserted (optional).
- The collection which is to be copied.
Code
import java.util.ArrayList;import java.util.Collections;import java.util.HashSet;public class AddAll {public static void main(String[] args) {// Declaring a list and adding elements:ArrayList<Integer> arr = new ArrayList<>();arr.add(10);arr.add(20);arr.add(30);// Declaring another list and adding elements:ArrayList<Integer> arr2 = new ArrayList<>();arr2.add(40);arr2.add(50);arr2.add(60);// Copying 'arr2' into 'arr' at index 1:arr.addAll(1, arr2);// Printing elementsarr.forEach(System.out::println);}}
1 of 2
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved