CopyOnWriteArrayList addAllAbsent() method in Java with Examples
Last Updated :
20 Dec, 2018
The addAllAbsent(E e) method of CopyOnWriteArrayList appends all of the elements in the specified collection that are not already contained in this list, to the end of this list, in the order that they are returned by the specified collection’s iterator.
Syntax:
public int addAllAbsent(Collection<E> collection)
Parameters: The function accepts a single mandatory parameter collection which specifies the collection to be appended to the list if it is not present.
Return Value: The function returns an integer value which is the number if elements added in the List.
Exception: This method throws NullPointerException if the specified collection is null.
Below programs illustrate the addAllAbsent() function:
Program 1:
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
CopyOnWriteArrayList<Integer> ArrLis
= new CopyOnWriteArrayList<Integer>();
ArrLis.add( 2 );
ArrLis.add( 3 );
ArrLis.add( 4 );
ArrLis.add( 7 );
System.out.println( "CopyOnWriteArrayList: "
+ ArrLis);
ArrayList<Integer> arr = new ArrayList<Integer>( 4 );
arr.add( 1 );
arr.add( 2 );
arr.add( 3 );
arr.add( 4 );
System.out.println( "The collection to be appended: "
+ arr);
System.out.println( "\nNumber of elements appended"
+ " using addAllAbsent() method: "
+ ArrLis.addAllAbsent(arr));
System.out.println( "Modified CopyOnWriteArrayList: "
+ ArrLis);
}
}
|
Output:
CopyOnWriteArrayList: [2, 3, 4, 7]
The collection to be appended: [1, 2, 3, 4]
Number of elements appended using addAllAbsent() method: 1
Modified CopyOnWriteArrayList: [2, 3, 4, 7, 1]
Program 2: To demonstrate NullPointerException
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
CopyOnWriteArrayList<Integer> ArrLis
= new CopyOnWriteArrayList<Integer>();
ArrLis.add( 2 );
ArrLis.add( 3 );
ArrLis.add( 4 );
ArrLis.add( 7 );
System.out.println( "CopyOnWriteArrayList: "
+ ArrLis);
ArrayList<Integer> arr = null ;
System.out.println( "The collection to be appended: "
+ arr);
try {
System.out.println( "\nTrying to append null collection\n" );
ArrLis.addAllAbsent(arr);
}
catch (Exception e) {
System.out.println(e);
}
}
}
|
Output:
CopyOnWriteArrayList: [2, 3, 4, 7]
The collection to be appended: null
Trying to append null collection
java.lang.NullPointerException
Reference: https://docs.oracle.com/javase/9/docs/api/java/util/concurrent/CopyOnWriteArrayList.html#addAllAbsent-java.util.Collection-
Share your thoughts in the comments
Please Login to comment...