Collections addAll() method in Java with Examples
Last Updated :
20 May, 2019
The addAll() method of java.util.Collections class 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. The behavior of this convenience method is identical to that of c.addAll(Arrays.asList(elements)), but this method is likely to run significantly faster under most implementations.
Syntax:
public static boolean
addAll(Collection c, T... elements)
Parameters: This method takes the following argument as a parameter
- c- the collection into which elements are to be inserted
- elements- the elements to insert into c
Return Value: This method returns true if the collection changed as a result of the call.
Exception: This method throws NullPointerException if elements contains one or more null values and c does not permit null elements, or if c or elements are null
Below are the examples to illustrate the addAll() method
Example 1:
import java.util.*;
public class GFG1 {
public static void main(String[] argv) throws Exception
{
try {
List<String> arrlist = new ArrayList<String>();
arrlist.add( "A" );
arrlist.add( "B" );
arrlist.add( "C" );
arrlist.add( "Tajmahal" );
System.out.println( "arrlist before operation : " + arrlist);
boolean b = Collections.addAll(arrlist, "1" , "2" , "3" );
System.out.println( "result : " + b);
System.out.println( "arrlist after operation : " + arrlist);
}
catch (NullPointerException e) {
System.out.println( "Exception thrown : " + e);
}
catch (IllegalArgumentException e) {
System.out.println( "Exception thrown : " + e);
}
}
}
|
Output:
arrlist before operation : [A, B, C, Tajmahal]
result : true
arrlist after operation : [A, B, C, Tajmahal, 1, 2, 3]
Output:
arrlist before operation : [A, B, C, Tajmahal]
result : true
arrlist after operation : [A, B, C, Tajmahal, 1, 2, 3]
Example 2: For NullPointerException
import java.util.*;
public class GFG1 {
public static void main(String[] argv) throws Exception
{
try {
List<String> arrlist = new ArrayList<String>();
arrlist.add( "A" );
arrlist.add( "B" );
arrlist.add( "C" );
arrlist.add( "Tajmahal" );
System.out.println( "arrlist before operation : " + arrlist);
System.out.println( "\nTrying to add the null value with arrlist" );
boolean b = Collections.addAll( null , arrlist);
System.out.println( "result : " + b);
System.out.println( "arrlist after operation : " + arrlist);
}
catch (NullPointerException e) {
System.out.println( "Exception thrown : " + e);
}
catch (IllegalArgumentException e) {
System.out.println( "Exception thrown : " + e);
}
}
}
|
Output:
arrlist before operation : [A, B, C, Tajmahal]
Trying to add the null value with arrlist
Exception thrown : java.lang.NullPointerException
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...