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.
public boolean contains(Object o)
This method takes the element to be checked for presence as a parameter.
This method returns true
if the passed element is present in the set
. Otherwise, it returns false
.
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"));}}
In the code above,
In line 1, we import the CopyOnWriteArraySet
class.
In line 4, we create a CopyOnWriteArraySet
object with the name set
.
In lines 5-7, we use the add
method of the set
object to add three elements ("1","2","3"
) to the set.
In line 10, we use the contains
method of the set
object to check if the element "1"
is present in the set. We get true
as a result.
In line 11, we use the contains
method to check if the element "4"
is present in the set. We get false
as a result, because "4"
is not present in the set.