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 anArrayList
. 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 toArrayList
.
public boolean containsAll(Collection<?> c)
The parameter is the collection that we check for in the list.
The containsAll()
method returns true
if all the elements of the passed collection are present in the list
. Otherwise, false
is returned.
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 elementsCopyOnWriteArrayList<Integer> list = new CopyOnWriteArrayList<>();// add three elements to itlist.add(1);list.add(2);list.add(3);// create a new arraylistArrayList<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 listSystem.out.println("If list contains all elements of list1 : "+ list.containsAll(list1));// create a new listArrayList<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 listSystem.out.println("If list contains all elements of list2 : "+ list.containsAll(list2));}}
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
.