优先队列和比较器
我试图从 localNodes 获取与哈希图距离最小的节点。当我更改距离散列图中的任何值时,问题是队列不会重新排序,我认为问题是因为我正在实现比较器接口,该接口将作为内部类并强制我将散列图声明为最终的。 有什么不同的方法吗?
final HashMap<Node, Double> distance = new HashMap<>();
PriorityQueue<Node> localNodes = new PriorityQueue<>(10,
new Comparator() {
@Override
public int compare(Object o1, Object o2) {
return distance.get((Node)o2).compareTo(distance.get((Node)o2) );
}
});
I am trying to get from localNodes the Node who has the minimum distance from the hashmap distance. the problem when am changing any value in the distance hashmap the queue is not reordered i think the problem is because i am implemting the comparator interface like that which will be as an inner class and enforce me to declare the hashmap as final.
is there any different method.
final HashMap<Node, Double> distance = new HashMap<>();
PriorityQueue<Node> localNodes = new PriorityQueue<>(10,
new Comparator() {
@Override
public int compare(Object o1, Object o2) {
return distance.get((Node)o2).compareTo(distance.get((Node)o2) );
}
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您无法更改已排序集合(例如
PriorityQueue
或SortedSet 并期望他们在该集合中的位置因此而改变。一方面,数据结构并不是为此而构建的。另一方面,在您的示例中,
PriorityQueue
不会收到您对HashMap
所做的任何更改的通知,因此即使它是设计的,它也无法响应。这样做。我不知道您如何使用此队列,但一种可能的解决方案是将节点存储在
HashMap
中,并在每次更改时创建一个新的PriorityQueue
哈希映射
。新创建的队列将具有正确的顺序。You can't change the relative ordering of elements (in this case, by changing the distance values they map to) that are already in a sorted collection such as a
PriorityQueue
orSortedSet
and expect their position in that collection to change as a result. For one thing, the data structures just aren't built for that. For another, in your example thePriorityQueue
will not be notified of any changes you make to theHashMap
so it wouldn't be able to respond to that even if it were designed to do so.I don't know how you're using this queue, but one possible solution would be to just store the nodes in your
HashMap
and create a newPriorityQueue
whenever you change theHashMap
. The newly created queue will have the correct ordering.你不能那样做(参见科林的回答)。我可以建议一种解决方法:
创建一个如下所示的
NodeEntry
对象:并使用
PriorityQueue
。但是,如果您更改NodeEntry
的value
,则不会发生任何变化。当某些值发生变化时,您无法对队列重新排序。You can't do it like that (See Colin's answer). I can suggest a workaround:
Make a
NodeEntry
object that looks like that:And use a
PriorityQueue<NodeEntry>
. But if you changeNodeEntry
'svalue
nothing will change. You can't reorder the queue when some value changes.