Collections.addAll(Collection<? super E>, E...): This method is available in java.util.Collections class of Java.
Syntax:
<E> boolean java.util.Collections.addAll(Collection<? super E> c, E... elements)
This method adds all of the specified element to the specified collection. Elements to be added may be specified individually or as an array.
Parameters:
c: the collection into which elements are to be inserted.
elements: the elements to insert into c.
Returns: true if the collection changed as a result of the call.
Throws:
1. UnsupportedOperationException - if c does not support the add operation.
2. NullPointerException - if elements contain one or more null values and c does not permit null elements, or if c or elements are null.
3. IllegalArgumentException - if some property of a value in elements prevents it from being added to c.
Approach 1: When no exception
Java
import java.util.ArrayList;import java.util.Collections;import java.util.List;public class CollectionsaddAll {public static void main(String[] args) {List<Integer> arrlist = new ArrayList<Integer>();Collections.addAll(arrlist, 1, 3, 4);System.out.println(arrlist);}}
Output:
[1, 3, 4]
Approach 2: NullPointerException
Java
import java.util.Collections;import java.util.List;public class CollectionsaddAll {public static void main(String[] args) {List<Integer> arrlist = null;Collections.addAll(arrlist, 1, 3, 4);System.out.println(arrlist);}}
Output:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.Collection.add(Object)" because "c" is null at java.base/java.util.Collections.addAll(Collections.java:5593)
No comments:
Post a Comment