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) );
}
});
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
PriorityQueueorSortedSetand 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 thePriorityQueuewill not be notified of any changes you make to theHashMapso 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
HashMapand create a newPriorityQueuewhenever you change theHashMap. The newly created queue will have the correct ordering.