CopyOnWriteArrayList
?CopyOnWriteArrayList
method 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 loss of 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.addAllAbsent
?addAllAbsent
is an instance method of the CopyOnWriteArrayList
which is used to insert elements in the given collection that are not present in the list to the end of the list.
The order of the 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 addAllAbsent()
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 int addAllAbsent(Collection<? extends E> c)
Collection<? extends E> c
: The collection to add.This method returns the number of elements added to the list.
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 objectCopyOnWriteArrayList<String> copyOnWriteArrayList = new CopyOnWriteArrayList<>();// add elements to copyOnWriteArrayListcopyOnWriteArrayList.add("inital-value");copyOnWriteArrayList.add("hello");// collection to add to the copyOnWriteArrayListList<String> stringList = Arrays.asList("hello", "educative");// print the list before addAllAbsent operationSystem.out.println("List before addAllAbsent operation - " + copyOnWriteArrayList);// addAllAbsent operation to add the contents of the list to copyOnWriteArrayListint numberOfElementsAdded = copyOnWriteArrayList.addAllAbsent(stringList);// Return value of the addAllAbsent operationSystem.out.println("The number of elements added " + numberOfElementsAdded);// print the list after addAllAbsent operationSystem.out.println("List after addAllAbsent operation - " + copyOnWriteArrayList);}}