What is the CopyOnWriteArrayList.addAll method in Java?
The addAll method adds all the elements of the passed collection to the end of the CopyOnWriteArrayList object.
Note:
CopyOnWriteArrayListis a thread-safe version of an ArrayList. All the write operations, likeaddandset, make a fresh copy underlying the array and perform the operation on the cloned array. Due to this, the performance is lower when compared to that of theArrayList. Read more about theCopyOnWriteArrayListmethod here.
Syntax
boolean addAll(Collection <? extends E > c)
Parameters
-
This method takes the collection object, which must be added to the list, as an argument.
-
This method throws a
NullPointerExceptionerror, if the argument isnull.
Return value
The addAll method returns true if the set changes as a result of the call, that is, if any one of the elements from the Collection is added to the list. Otherwise, it returns false.
Code
import java.util.concurrent.CopyOnWriteArrayList;import java.util.ArrayList;class AddAllDemo {public static void main( String args[] ) {//create a new CopyOnWriteArrayListCopyOnWriteArrayList<Integer> list = new CopyOnWriteArrayList<>();list.add(1);list.add(2);list.add(3);// create a new list that will be added to the existing listArrayList<Integer> elementsToBeAdded = new ArrayList<>();elementsToBeAdded.add(1);elementsToBeAdded.add(4);elementsToBeAdded.add(5);System.out.println("The list is "+ list);System.out.println("elementsToBeAdded - "+ elementsToBeAdded);// use addAdll mehod to add elementsToBeAdded to the listSystem.out.println("\nCalling list.addAll(elementsToBeAdded) -> Is list changed - " + list.addAll(elementsToBeAdded));System.out.println("The list is "+ list);}}
Explanation
In the code given above, the following steps were taken:
-
In lines 1 and 2, we imported the
CopyOnWriteArrayListmethod and theArrayListclasses. -
From lines 7 to 10, we created a new
CopyOnWriteArrayListobject with the namelistand used theaddmethod to add three elements (1,2, and3) to thelistobject. -
From lines 13 to 16, we created a new
ArrayListobject with the nameelementsToBeAddedand used theaddmethod to add three elements (1,4, and5) to theelementsToBeAddedobject. -
In line 22, we used the
addAllmethod to add all the elements of theelementsToBeAddedlist to thelist. Now, thelistwill be[1,2,3,1,4,5].