What is CopyOnWriteArrayList.containsAll() method in Java?
What is CopyOnWriteArrayList?
CopyOnWriteArrayListis a thread-safe implementation of theArrayListclass, which does not carry the requirement for synchronization.- The whole content of the
CopyOnWriteArrayListdata structure is duplicated on to a new internal copy when we use any of the altering methods, such as add() or delete(). Hence, the list can be iterated in a safe way during the modification of the list, concurrently. - The data structure’s properties make it particularly helpful in situations when we iterate over it more frequently than we alter it.
- If adding items is a typical activity, then
CopyOnWriteArrayListisn’t the appropriate data structure to use, as the extra copies will almost always result in poor performance.
containsAll
containsAll is an instance method of the CopyOnWriteArrayList data structure, which is used to check if all the elements of the given collection are present in the list or not.
The containsAll method is defined in the CopyOnWriteArrayList class. The CopyOnWriteArrayList class is defined in the java.util.concurrent package. To import the CopyOnWriteArrayList class, we will check the following import statement:
import java.util.concurrent.CopyOnWriteArrayList;
Syntax
public boolean containsAll(Collection<?> c)
Parameters
Collection<?> c: The collection that needs to be checked.
Return value
This method returns true if the list contains all the elements of the given collection. Otherwise, it returns false.
Code
import java.util.Arrays;import java.util.List;import java.util.concurrent.CopyOnWriteArrayList;public class Main{public static void main(String[] args) {// Create the CopyOnWriteArrayList objectCopyOnWriteArrayList<String> copyOnWriteArrayList = new CopyOnWriteArrayList<>();// add elements to the end of the copyOnWriteArrayListcopyOnWriteArrayList.add("inital-value");copyOnWriteArrayList.add("hello");// add element at the specified indexint index = 1;copyOnWriteArrayList.add(index, "educative");// collection to checkList<String> stringList = Arrays.asList("hello", "educative");// check if the copyOnWriteArrayList contains all elements of stringListSystem.out.printf("%s.containsAll(%s) = %s ", copyOnWriteArrayList, stringList, copyOnWriteArrayList.containsAll(stringList));}}
Code explanation
- Line 9: We create the
CopyOnWriteArrayListobject - Lines 12 and 13: We add elements to the end of the
copyOnWriteArrayListobject. - Line 17: We add an element at the specified index.
- Line 20: We see the collection that needs to be checked.
- Line 23: We check if the
copyOnWriteArrayListobject contains all the elements of thestringListor not.