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:

  1. The static method in the Collections class.
  2. 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

  1. The collection in which elements are to be added.
  2. 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 elements
arr.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

  1. The index of the caller array at which the elements are to be inserted (optional).
  2. 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 elements
arr.forEach(System.out::println);
}
}
1 of 2

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved