Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if queue contains object

Tags:

java

For a java.util.concurrent.BlockingQueue

By Java specification, for a method contains(Object o)

If I have previously inserted a new object like:

Task task = new Task("taskname", "somevalue"); 
queue.put(task);

on it. And later try to do this:

Task task = new Task("taskname", "somevalue"); 
queue.contains(task);

Since BlockingQueue is just an interface, by Java specification, should this return true or not?

The Task class is Serializable so the comparison will be based on field values right?

like image 485
quarks Avatar asked Feb 18 '13 06:02

quarks


People also ask

How do you check if a queue contains an element?

Check if Queue Contains Element You can check if a Java Queue contains a certain element via its contains() method. The contains() method will return true if the Queue contains the given element, and false if not.

How do you check if an item is in a queue Python?

To check if an element is in a queue in Python: Access the queue attribute on the queue to get a deque object. Use the in operator to check if the element is in the queue. The in operator tests for membership.

Is empty queue Java?

The isEmpty() method of ConcurrentLinkedQueue is used to check if this queue is empty or not. It returns true if ConcurrentLinkedQueue contains zero number of elements means if the ConcurrentLinkedQueue is empty. Returns: This method returns true if this ConcurrentLinkedQueue contains zero number of elements.


2 Answers

The behavior depends on if Task class overrides equals method. Depending on the logic of equals method, these two Tasks may/may not be equal.

From the Java docs of Blocking queue

boolean contains(Object o)

Returns true if this queue contains the specified element. More formally, returns true if and only if this queue contains at least one element e such that o.equals(e).

If the equals method is not overridden, then Java will use the equals method of Object for equality check(which checks if object references are equal).

   public boolean equals(Object obj) {
    return (this == obj);
}

Since these are two distinct objects, so object reference id will be different and hence contains will return false.

like image 64
MoveFast Avatar answered Oct 14 '22 08:10

MoveFast


Since BlockingQueue is just an interface, by Java specification, should this return true or not?

This is a weird question. As long as queue object is created, it should behave as promised by its interface(BlockingQueue).

Interface is abstract in that it cannot be instantiated by itself, but it's a common contract for all objects created by those classes that implement it.

As for your concreate question, whether queue.contains(task) return true depends on how class Task defines its equals method.

like image 28
Hui Zheng Avatar answered Oct 14 '22 07:10

Hui Zheng