The ConcurrentLinkedQueue
is a thread-safe unbounded queue. The elements are ordered by FIFO (First-In-First-Out), and they are inserted at the tail (end) and retrieved from the head (start) of the queue. The null
elements are not allowed as element of the queue. We can use the ConcurrentLinkedQueue
when multiple threads are sharing a single queue.
The contains
method can be used to check if an element is present in the queue.
public boolean contains(Object o)
This method takes the element to be checked for availability as an argument.
This method returns true
if the element is present in the queue. Otherwise, false
will be returned.
The code below demonstrates how to use the contains
method.
import java.util.concurrent.ConcurrentLinkedQueue;class Contains {public static void main( String args[] ) {ConcurrentLinkedQueue<String> queue = new ConcurrentLinkedQueue<>();queue.add("1");queue.add("2");queue.add("3");System.out.println("The queue is " + queue);System.out.println("queue.contains(1) - " + queue.contains("1"));System.out.println("queue.contains(4) - " + queue.contains("4"));}}
In the above code:
In line 1 we imported the ConcurrentLinkedQueue
from the java.util.concurrent
package.
In line 4 an object is created for the ConcurrentLinkedQueue
class with the name queue
.
From lines 5 to 7 three elements were added to the queue
object.
In lines 9 and 10 we used the contains
method to check if an element is present in the queue.
For the argument "1"
, the contains
method returns true
. For the argument "4"
, the contains
method returns false
.