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 addAll()
method returns true
if the collection changes as a result of elements being added into it; otherwise, it will return false
.
Collections.addAll()
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);}}
addAll()
This method is defined only in the classes that implement the Collection interface (e.g., ArrayList, HashSet, etc.).
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);}}
Free Resources