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: CopyOnWriteArrayList is a thread-safe version of an ArrayList. All the write operations, like add and set, 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 the ArrayList. Read more about the CopyOnWriteArrayList method 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 NullPointerException error, if the argument is null.

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 CopyOnWriteArrayList
CopyOnWriteArrayList<Integer> list = new CopyOnWriteArrayList<>();
list.add(1);
list.add(2);
list.add(3);
// create a new list that will be added to the existing list
ArrayList<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 list
System.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 CopyOnWriteArrayList method and the ArrayList classes.

  • From lines 7 to 10, we created a new CopyOnWriteArrayList object with the name list and used the add method to add three elements (1, 2, and 3) to the list object.

  • From lines 13 to 16, we created a new ArrayList object with the name elementsToBeAdded and used the add method to add three elements (1, 4, and 5) to the elementsToBeAdded object.

  • In line 22, we used the addAll method to add all the elements of the elementsToBeAdded list to the list. Now, the list will be [1,2,3,1,4,5].

Free Resources