The containsAll()
method checks if all the elements of a specific collection object are also present in the CopyOnWriteArraySet
object.
Note:
CopyOnWriteArraySet
is a thread-safe version of. set A collection that contains no duplicate elements. CopyOnWriteArraySet
internally usesCopyOnWriteArrayList
for its operations. All of the write operations, likeadd
andset
, make a fresh copy of the underlying array and operate on the cloned array. Read more aboutCopyOnWriteArraySet
here.
public boolean containsAll(Collection<?> c)
The containsAll()
method takes the collection that we check for in the set as an argument.
The containsAll()
method returns true
if all the elements of the passed collection are present in the set
. Otherwise, it returns false
.
The code below demonstrates how we can use the containsAll()
method.
import java.util.concurrent.CopyOnWriteArraySet;import java.util.ArrayList;class ContainsAllExample {public static void main( String args[] ) {// create a CopyOnWriteArraySet object which can contain integer elementsCopyOnWriteArraySet<Integer> set = new CopyOnWriteArraySet<>();// add three elements to itset.add(1);set.add(2);set.add(3);// create a new arraylistArrayList<Integer> list1 = new ArrayList<>();list1.add(1);list1.add(3);System.out.println("The set is "+ set);System.out.println("\nlist1 is "+ list1);// use contiansAll method to check if all element of list1 is present in listSystem.out.println("If set contains all elements of list1 : "+ set.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 set contains all elements of list2 : "+ set.containsAll(list2));}}
Lines 1 to 2: We import the CopyOnWriteArraySet
and ArrayList
classes.
Line 6: We create an object named set
for the CopyOnWriteArraySet
class.
Lines 8 to 10: We add three elements (1
, 2
, and 3
) to the created set
object.
Line 13: We create a new ArrayList
object named list1
and add the elements 1
and 3
to it.
Line 20: We call the containsAll()
method to check if all the elements of list1
are present in set
. In this case, the condition returns true
because all the elements (1
and 3
) of list1
are also present in set
.
Line 2*: We create a new ArrayList
object named list2
and add the element 4
to it.
Line 29: We call the containsAll()
method to check if all the elements of list2
are present in set
. In this case, the condition returns false
because element 4
of list2
is not present in set
.