What is CopyOnWriteArrayList.contains method() in Java?
What is CopyOnWriteArrayList?
- The
CopyOnWriteArrayListis a thread-safe implementation ofArrayListwithout the requirement for synchronization. - The whole content of the
CopyOnWriteArrayListis duplicated onto a new internal copy when we use any of the altering methods, such asadd()ordelete(). 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 it more frequently as compared to when we alter it.
- If adding items is a typical activity,
CopyOnWriteArrayListisn’t the appropriate data structure to use, as the extra copies will almost always result in poor performance.
What is the contains() method?
contains() is an instance method of the CopyOnWriteArrayList that is used to check whether the list contains the given element or not.
The contains() method is defined in the CopyOnWriteArrayList class. The CopyOnWriteArrayList class is defined in the java.util.concurrent package. To import the CopyOnWriteArrayList class, check the following import statement.
import java.util.concurrent.CopyOnWriteArrayList;
Syntax
public boolean contains(Object o)
Parameters
Object o: This is the object to check.
Return value
This method returns true if the list contains the given object. Otherwise, it returns false.
Code
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");// Object to checkString stringToCheck = "hello";// check if the stringToCheck is present in stringToCheckSystem.out.printf("%s.contains(%s) = %s ", copyOnWriteArrayList, stringToCheck, copyOnWriteArrayList.contains(stringToCheck));}}
Explanation
-
Line 1: We import the
CopyOnWriteArrayListclass. -
Line 7: We create an object of
CopyOnWriteArrayListwith the namecopyOnWriteArrayList. -
Lines 10-11: We add elements to the end of
copyOnWriteArrayList. -
Line 14: We define the index at which we want to insert the element.
-
Line 15: We pass the index defined in line 14 and the element to be inserted as arguments in the
add()method. -
Line 18: We assign the value
helloto the stringstringToCheck. -
Line 21: We check whether the list contains the element using the
contains()method and print the result to the console.