What is the CopyOnWriteArrayList.addAllAbsent method() in Java?
What is CopyOnWriteArrayList?
- The
CopyOnWriteArrayListmethod is a thread-safe implementation ofArrayListwithout the requirement for synchronization. - The whole content of the
CopyOnWriteArrayListis duplicated into a new internal copy when we use any of the altering methods, such asadd()ordelete(). Hence, the list can be iterated in a safe way, without any fear of loss of data, while modifying it simultaneously. - The data structure’s properties make it particularly helpful in situations when we iterate over it more frequently than we alter it.
- If adding items is a typical activity,
CopyOnWriteArrayListisn’t the appropriate data structure to use, as the extra copies will almost always result in poor performance.
What is 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;
Syntax
public int addAllAbsent(Collection<? extends E> c)
Parameters
Collection<? extends E> c: The collection to add.
Return value
This method returns the number of elements added to the list.
Code
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);}}