Java Collections - addAll() Method
The java.util.Collections.addAll() method is used to add all of the specified elements to the specified collection. Elements to be added may be specified individually or as an array.
Syntax
public static <T> boolean addAll(Collection<? super T> c, T... elements)
Here, T is the type of element to add and of the collection.
Parameters
c |
Specify the collection into which elements are to be inserted. |
elements |
Specify the elements to insert into c. |
Return Value
Returns true if the collection changed as a result of the call.
Exception
- Throws UnsupportedOperationException, if c does not support the add operation.
- Throws NullPointerException, if elements contains one or more null values and c does not permit null elements, or if c or elements are null.
- Throws IllegalArgumentException, if some property of a value in elements prevents it from being added to c.
Example:
In the example below, the java.util.Collections.addAll() method is used to add all of the specified elements to the specified collection.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating a vector Vector<Integer> Vec = new Vector<Integer>(); //populating vector Vec.add(10); Vec.add(20); Vec.add(30); //printing vector System.out.println("Vec contains: " + Vec); //add more values to the collection Collections.addAll(Vec, 40, 50); //printing vector System.out.println("Vec contains: " + Vec); //add more values to the collection using array Integer Arr[] = {60, 70}; Collections.addAll(Vec, Arr); //printing vector System.out.println("Vec contains: " + Vec); } }
The output of the above code will be:
Vec contains: [10, 20, 30] Vec contains: [10, 20, 30, 40, 50] Vec contains: [10, 20, 30, 40, 50, 60, 70]
❮ Java.util - Collections