CopyOnWriteArrayList
is a thread-safe implementation of ArrayList
without the requirement for synchronization.CopyOnWriteArrayList
is duplicated into a new internal copy when we use any of the altering methods, such as add()
or delete()
. Hence, the list can be iterated in a safe way, without any fear of losing data, while modifying it simultaneously.CopyOnWriteArrayList
isn’t the appropriate data structure to use as the extra copies will almost always result in poor performance.addAll()
is an instance method of the CopyOnWriteArrayList
which is used to insert all the elements in the given collection to the end of the list. The order of insertion of the elements at the end of the list is the order in which the elements are returned by the iterator of the specified collection.
The addAll()
method is defined in the CopyOnWriteArrayList
class. The CopyOnWriteArrayList
class is defined in the java.util.concurrent
package. To import the CopyOnWriteArrayList
class, check the following import statement.
import java.util.concurrent.CopyOnWriteArrayList;
public boolean addAll(Collection<? extends E> c)
Collection<? extends E> c
: The collection to append to the list.This method returns true
if the list is changed/modified. Otherwise, it returns false
.
import java.util.Arrays; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; public class Main{ public static void main(String[] args) { // Create the CopyOnWriteArrayList object CopyOnWriteArrayList<String> copyOnWriteArrayList = new CopyOnWriteArrayList<>(); // add element to copyOnWriteArrayList copyOnWriteArrayList.add("inital-value"); // collection to add to the copyOnWriteArrayList List<String> stringList = Arrays.asList("hello", "educative"); // print the list before addAll operation System.out.println("List before addAll operation - " + copyOnWriteArrayList); // addAll operation to add the contents of the list to copyOnWriteArrayList boolean addAllReturnValue = copyOnWriteArrayList.addAll(stringList); // Return value of the addAll operation System.out.println("Return value of the addAll operation - " + addAllReturnValue); // print the list after addAll operation System.out.println("List after addAll operation - " + copyOnWriteArrayList); } }
RELATED TAGS
CONTRIBUTOR
View all Courses