Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

contains
java
communitycreator

What is the ConcurrentLinkedQueue.contains() method in Java?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

Syntax

public boolean contains(Object o)

Parameters

This method takes the element to be checked for availability as an argument.

Return value

This method returns true if the element is present in the queue. Otherwise, false will be returned.

Code

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"));
}
}

Explanation

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.

RELATED TAGS

contains
java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring