What is the CopyOnWriteArrayList.containsAll method in Java?

The containsAll() method checks if all elements of the specific collection object are present in the CopyOnWriteArrayList object.

Note:CopyOnWriteArrayList is a thread-safe version of an ArrayList. All the write operations such as add or set make a fresh copy of the underlying array and perform the operation in the cloned array. Due to this, the performance is lower compared to ArrayList.

Syntax

public boolean containsAll(Collection<?> c)

Parameters

The parameter is the collection that we check for in the list.

Return value

The containsAll() method returns true if all the elements of the passed collection are present in the list. Otherwise, false is returned.

Code

The code below demonstrates the use of the containsAll() method:

import java.util.concurrent.CopyOnWriteArrayList;
import java.util.ArrayList;
class ContainsAllExample {
public static void main( String args[] ) {
// create a CopyOnWriteArrayList object which can contain integer elements
CopyOnWriteArrayList<Integer> list = new CopyOnWriteArrayList<>();
// add three elements to it
list.add(1);
list.add(2);
list.add(3);
// create a new arraylist
ArrayList<Integer> list1 = new ArrayList<>();
list1.add(1);
list1.add(3);
System.out.println("The list is "+ list);
System.out.println("\nlist1 is "+ list1);
// use contiansAll method to check if all element of list1 is present in list
System.out.println("If list contains all elements of list1 : "+ list.containsAll(list1));
// create a new list
ArrayList<Integer> list2 = new ArrayList<>();
list2.add(4);
System.out.println("\nlist2 is "+ list2);
// use contiansAll method to check if all element of list2 is present in list
System.out.println("If list contains all elements of list2 : "+ list.containsAll(list2));
}
}
Using the containsAll method

Explanation

  • Lines 1 to 2: We import the CopyOnWriteArrayList and ArrayList classes.

  • Line 6: We create an object named list for the CopyOnWriteArrayList class.

  • Lines 8 to 10: We add three elements (1,2,3) to the created list object.

  • Line 13: We create a new ArrayList object named list1 and add the elements (1,3) to it.

  • Line 20: We call the containsAll() method to check if all the elements of list1 are present in list. In this case, the condition returns true because all the elements (1,3) of list1 are present in list.

  • Line 23: We create a new ArrayList object named list2 and add the element 4 to it.

  • Line 29: We again call the containsAll() method to check if all elements of list2 are present in list. In this case, the condition returns false. This is because element 4 of list2 is not present in list.

Free Resources