In this post under Java, I will show with example the purpose of static “addAll” method in “Collections” class.
The “addAll” method populates a collection with the given list of elements.
This method takes two arguments
1) the collection that it has to fill or populate
2) variable length arument that will contain the elements that has to be added to the collection.
Below is the complete main code for your reference
Main class
1 package core.collection;
2
3 import java.util.ArrayList;
4 import java.util.Collections;
5 import java.util.List;
6
7 public class CollectionAddAllDemo {
8 public static void main(String[] args) {
9 List<Integer> integerList = new ArrayList<>(0);
10 Collections.addAll(integerList, 1, 2, 3, 4);
11
12 System.out.println(integerList);
13 }
14 }
In the above code, at line 9 I create an empty list of element type Integer named “integerList”.
At line 10, I call the “Collections” “addAll” method and pass the “integerList” and list of numbers.
At line 12, I am printing the list.
Below is the output
In this way we can populate a collection with multiple elements in one single method call.
Output
[1, 2, 3, 4]