What is the CopyOnWriteArrayList.addIfAbsent method in Java?
The addIfAbsent method can be used to add an element to the end of the CopyOnWriteArrayList object if the element is not already present in the list.
Note:
CopyOnWriteArrayListis a thread-safe version of anArrayList. All the write operations, likeaddandset, make a fresh copy underlying the array and perform the cloned array operation. Due to this, the performance is lower when compared to that ofArrayList. Read more aboutCopyOnWriteArrayListhere.
Syntax
public boolean addIfAbsent(E e)
Parameters
This method takes the element to be appended to the list as an argument.
Return value
The addIfAbsent method returns true if the element is added. Otherwise, it returns false.
Code
The code below demonstrates how we can use the addIfAbsent method.
import java.util.concurrent.CopyOnWriteArrayList;class AddIfAbsentExample {public static void main( String args[] ) {// create CopyOnWriteArraySet object which can store integer objectCopyOnWriteArrayList<Integer> list = new CopyOnWriteArrayList<>();// add elememtslist.add(1);list.add(2);list.add(3);// Print listSystem.out.println("The list is: " + list);// call addIfAbsent for element 4System.out.println("\nlist.addIfAbsent(4) : " + list.addIfAbsent(4));System.out.println("The list is: " + list);// call addIfAbsent for element 1System.out.println("\nlist.addIfAbsent(1) : " + list.addIfAbsent(1));System.out.println("The list is: " + list);}}
Code explanation
In the code given above:
-
In line 1, we import the
CopyOnWriteArrayListclass. -
In line 5, we create a
CopyOnWriteArrayListobject with the namelist. -
In lines 8–10, we use the
addmethod to add elements to thelist. -
In line 16, we use the
addIfAbsentmethod with4as an argument. The element4is not already present in the list, so it is appended to the list and the method returnstrue. -
In line 20, we use the
addIfAbsentmethod with1as an argument. The element1is already present in the list, so the method returnsfalse.