是否有一个队列(PriorityQueue)实现也是一个集合? [英] Is there a Queue (PriorityQueue) implementation which is also a Set?
问题描述
我正在寻找 PriorityQueue 实现也是一个 Set一>.
I'm looking for a PriorityQueue implementation which is also a Set.
compareTo
实现,如果它的元素不能要求与 equals
的实现保持一致.
The compareTo
implementation if its elements must not have the requirement to be consistent with the implementation of equals
.
有没有这样的java实现?
Is there somewhere such a implementation for java?
更新:我现在使用 SortedSet 作为内部集合来实现它.所以我只需要实现缺少的方法来满足队列接口.我还忘了提到它也必须是一个有界队列,因此它具有容量并在达到容量时丢弃集合的最后一个元素.
Update: I implemented it now using a SortedSet as the internal collection. So I only had to implement the missing methods to satisfy the queue interface. I also forgot to mention that it also had to be a bounded queue, so it features a capacity and discards the last element of the set if capacity is reached.
推荐答案
如果队列具有类似 Set"的行为就足够了,我只是不想接受重复的条目,那么我认为,简单的解决方案可能是将 PriorityQueue
子类化并覆盖 add()
、addAll()
和 offer()
方法喜欢:
If it's sufficient to have a queue with a 'Set-like' behaviour, iaw you just don't want to accept duplicate entries, then I think, an easy solution could be to subclass PriorityQueue
and override the add()
, addAll()
and offer()
methods like:
@Override
public boolean offer(E e) {
if (contains(e)) {
return false;
} else {
return super.offer(e);
}
}
顺便说一句 - add()
在内部调用 offer()
,所以也许只需覆盖 offer()
方法并执行那里的支票.
BTW - add()
calls offer()
internally, so maybe it's even enough to just override the offer()
method and do the check there.
这篇关于是否有一个队列(PriorityQueue)实现也是一个集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!