fringe = new PriorityQueue<Node>(10,new Comparator<Node>(){
@Override
public int compare(Node node1,Node node2)
{
if (f(node1)>f(node2))
return 1;
else
return -1;
}
});
I declared a PQ to store some nodes and i want to store the nodes in non-decreasing order according to the f value.function f(Node node) is to calculate the f value for the node. so i override the comparator but right now i found that some nodes with larger f value are placed before the ones with smaller f value in the queue, i checked all over but still cannot find what goes wrong, i assume maybe it is the PQ declaration’s problem. Anyone can help me? Thanks in advance!
As stated by @izomorphius, PriorityQueue does not guarantee full ordering, only that the head is always minimal.
If you want full order – you might want to chose one of these possiblities:
TreeSet– but note it will not allow duplicates. Also, as stated by @JoonasPulakka, here you will probably want to overrideequals()andhashCode()as well.List– populate it [unordered] and then useCollections.sort(List,Comparator)to sort it according to your comparatorNode[]], populate it [unordered] and then useArrays.sort()to sort it according to your comparator.EDIT:
Your editted Comparator does not enforce full ordering, and thus the result of using it is undefined:
let
a,bbe twoNodes such thatf(a) == f(b)But the javadocs states:
Thus, the result of using this [the editted] comparator is undefined.
EDIT2:
Your comments suggest you are looking for a second criteria – of “adding time”. You can add another field
long timestampto yourNodeobject, and in yourComparatorreturn a result based on this field if and only iff(node1) == f(node2). This will guarantee consistency, and will achieve the wanted feature.Note: this field will be initialized once [and only once!] when you add an element to the queue for the first time [or when the object is created, if it’s an option].