CopyOnWriteArrayList
?CopyOnWriteArrayList
is a thread-safe implementation of ArrayList
without the requirement for synchronization.CopyOnWriteArrayList
is duplicated onto 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.CopyOnWriteArrayList
isn’t the appropriate data structure to use, as the extra copies will almost always result in poor performance.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;
public boolean contains(Object o)
Object o
: This is the object to check.This method returns true
if the list contains the given object. Otherwise, it returns false
.
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));}}
Line 1: We import the CopyOnWriteArrayList
class.
Line 7: We create an object of CopyOnWriteArrayList
with the name copyOnWriteArrayList
.
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 hello
to the string stringToCheck
.
Line 21: We check whether the list contains the element using the contains()
method and print the result to the console.