What is the CopyOnWriteArraySet.contains method in Java?
CopyOnWriteArraySet is a thread-safe version of CopyOnWriteArrayList for its operations. For all the write operations like add or set, it makes a fresh copy of the underlying array and operates on the cloned array. Read more about CopyOnWriteArraySet here.
The contains method is used to check if an element is present in the CopyOnWriteArraySet object.
Syntax
public boolean contains(Object o)
Parameter
This method takes the element to be checked for presence as a parameter.
Return value
This method returns true if the passed element is present in the set. Otherwise, it returns false.
Code
The code below demonstrates how to use the contains method.
import java.util.concurrent.CopyOnWriteArraySet;class Contains {public static void main( String args[] ) {CopyOnWriteArraySet<String> set = new CopyOnWriteArraySet<>();set.add("1");set.add("2");set.add("3");System.out.println("The set is " + set);System.out.println("Check if 1 present in the set : " + set.contains("1"));System.out.println("Check if 4 present in the set : " + set.contains("4"));}}
Explanation
In the code above,
-
In line 1, we import the
CopyOnWriteArraySetclass. -
In line 4, we create a
CopyOnWriteArraySetobject with the nameset. -
In lines 5-7, we use the
addmethod of thesetobject to add three elements ("1","2","3") to the set. -
In line 10, we use the
containsmethod of thesetobject to check if the element"1"is present in the set. We gettrueas a result. -
In line 11, we use the
containsmethod to check if the element"4"is present in the set. We getfalseas a result, because"4"is not present in the set.