【发布时间】:2017-03-29 18:34:31
【问题描述】:
java.util.concurrent.BlockingQueue 有一个方便的contains 方法:
/**
* Returns {@code true} if this queue contains the specified element.
* More formally, returns {@code true} if and only if this queue contains
* at least one element {@code e} such that {@code o.equals(e)}.
*
* @param o object to be checked for containment in this queue
* @return {@code true} if this queue contains the specified element
* @throws ClassCastException if the class of the specified element
* is incompatible with this queue
* (<a href="../Collection.html#optional-restrictions">optional</a>)
* @throws NullPointerException if the specified element is null
* (<a href="../Collection.html#optional-restrictions">optional</a>)
*/
public boolean contains(Object o);
我的需要更具体一点:应用predicate / 搜索条件。有什么办法可以做到这一点
Using a ArrayBlockQueue
Invoking toArray
这会起作用..但是如果队列很大怎么办?这可能会导致内存分配问题。
【问题讨论】:
-
这对于多个队列来说似乎是一个很好的例子,而不是试图将一个队列硬塞到一些奇怪的、非队列式的行为中。
-
@pvg 搜索基于在消息中查找特定 ID。基于固定谓词的“多个”队列并非如此。采用这种方法时,我们需要为每条消息创建一个队列。
-
如果消息 ID 是唯一的,您只需覆盖 .equals。或者设置某种优先级。如果您必须识别特定消息,那么使用强加命令的队列有什么意义?您应该描述您要解决的问题,而不是“如何使队列表现得像非队列”。
-
'你所要做的就是覆盖 .equals。'容器是一个匿名元组:它需要将队列的元素更改为不同的类。也许这是一个合理的方法 - 但它 与问题不同。回复:使队列像非队列一样。我在过去十年中已经构建了自定义排队系统。这是一个队列,要求进行搜索并不能让它不是这样。
-
要求它进行搜索是要求无序访问。当然,您可以将其添加到队列中。或者您可以使用另一个数据结构来跟踪您想要乱序访问的任何内容。但是你不会在队列中找到很多对这类东西的丰富支持,因为一般来说,这不是队列的主要工作。如您所见,反映在 JDK 提供的队列中。
标签: java queue blockingqueue