如何比较Java PriorityQueue中的任意元素?
我有一个 PriorityQueue
,其中有一个具有优先级的元素。现在我想以不同的优先级再次添加相同的元素,并仅保留具有较高优先级的元素。我想过将新元素与已存在的元素进行比较,然后决定是保留旧元素还是替换,但我找不到一种方法将新元素与 PriorityQueue 中的任意元素进行比较>。
I have a PriorityQueue
that has an element with a priority. Now I want to add the same element again with a different priority and keep only the one with higher priority. I thought of checking the new element against the already present one and then deciding whether to keep the old one or replace, but I can't find a way to compare my new element against an arbitrary element from the PriorityQueue
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
PriorityQueue 并不是要访问其中的任意元素,它的设计目的是允许快速访问单独的头部。如果您需要频繁执行此操作,
java.util.TreeSet
可能是更好的数据结构。但是,您可以通过迭代
PriorityQueue
[使用Iterator
] 并在找到匹配项时中断来访问任何元素。在任何情况下,对于PriorityQueue
来说,获取任意元素都无法获得比O(n)
更好的性能,因为它的设计初衷并不是这样做。a
PriorityQueue
was not meant to access an arbitrary element in it, it is designed to allow fast access to the head alone. If you need to do this operation frequently, probably ajava.util.TreeSet
will be a better data structure.However, you can access any element by iterating
PriorityQueue
[using anIterator
] and breaking when you find your match. You cannot get performance better thenO(n)
for getting an arbitrary element in any case for aPriorityQueue
, because it was not designed to do it.