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: 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 cloned array operation. Due to this, the performance is lower when compared to that of ArrayList. Read more about CopyOnWriteArrayList here.

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 object
CopyOnWriteArrayList<Integer> list = new CopyOnWriteArrayList<>();
// add elememts
list.add(1);
list.add(2);
list.add(3);
// Print list
System.out.println("The list is: " + list);
// call addIfAbsent for element 4
System.out.println("\nlist.addIfAbsent(4) : " + list.addIfAbsent(4));
System.out.println("The list is: " + list);
// call addIfAbsent for element 1
System.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 CopyOnWriteArrayList class.

  • In line 5, we create a CopyOnWriteArrayList object with the name list.

  • In lines 8–10, we use the add method to add elements to the list.

  • In line 16, we use the addIfAbsent method with 4 as an argument. The element 4 is not already present in the list, so it is appended to the list and the method returns true.

  • In line 20, we use the addIfAbsent method with 1 as an argument. The element 1 is already present in the list, so the method returns false.

Free Resources