The addIfAbsent() method of CopyOnWriteArrayList in Java


The addIfAbsent() method appends the element if it is not in the list. If the element is already in the list, then FALSE is returned.

The syntax is as follows.

public boolean addIfAbsent(E ele)

Here, ele is the element to be added to this list, if it is not already in the list.

To work with CopyOnWriteArrayList class, you need to import the following package.

import java.util.concurrent.CopyOnWriteArrayList;

The following is an example to implement CopyOnWriteArrayList class addIfAbsent() method in Java.

Example

 Live Demo

import java.util.concurrent.CopyOnWriteArrayList;
public class Demo {
   public static void main(String[] args) {
      CopyOnWriteArrayList<Integer> arrList = new CopyOnWriteArrayList<Integer>();
      arrList.add(30); arrList.add(40); arrList.add(60); arrList.add(70); arrList.add(90); arrList.add(100); arrList.add(120);
      System.out.println("CopyOnWriteArrayList = " + arrList);
      System.out.println("Add an element if not in the List = "+arrList.addIfAbsent(70));
   }
}

Output

CopyOnWriteArrayList = [30, 40, 60, 70, 90, 100, 120]
Add an element if not in the List = false

Let us see another example wherein the element to be appended is not already present in the list

Example

 Live Demo

import java.util.concurrent.CopyOnWriteArrayList;
public class Demo {
   public static void main(String[] args) {
      CopyOnWriteArrayList<Integer> arrList = new CopyOnWriteArrayList<Integer>();
      arrList.add(30);
      arrList.add(40);
      arrList.add(60);
      arrList.add(70);
      arrList.add(90);
      arrList.add(100);
      arrList.add(120);
      System.out.println("CopyOnWriteArrayList = " + arrList);
      System.out.println("Add an element if not in the List = "+arrList.addIfAbsent(150));
      System.out.println("Updated CopyOnWriteArrayList = " + arrList);
   }
}

Output

CopyOnWriteArrayList = [30, 40, 60, 70, 90, 100, 120]
Add an element if not in the List = true
Updated CopyOnWriteArrayList = [30, 40, 60, 70, 90, 100, 120, 150]

Updated on: 30-Jul-2019

431 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements