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?
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.
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.
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.
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With