How do I fix a Java Priority-Queue to correctly sort by a specific property?
I have a Java PriorityQueue for sorting objects from a specific class I made called Node. I want it to sort the Nodes by their getData() method. I tried the following code (using a comparator), but it did not work. When I called the priority queue's "poll" method, it did not return the lowest results first, but in a seemingly random order. How do I fix it? Thanks!
PriorityQueue<Node> pq = new PriorityQueue<Node>(hm.size(),
new Comparator<Node>( ) {
// override the compare method
开发者_开发百科 public int compare(Node i, Node j) {
if (i.getData()<j.getData()){
return i.getData(); //It should sort by the Node's getData method.
}
return j.getData();
A comparator needs to return -1 (a negative number), 0 or +1 (a positive number) depending on whether the first operand is less-than, equal-to or greater-than the second operand. You are returning the data itself which won't do what you want.
Rewrite the compare method:
public int compare(Node i, Node j) {
return i.getData() - j.getData()
}
This will follow requirements of compare method to return value less, equal or more than zero depending on comparison result.
精彩评论