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();
Rewrite the compare method:
This will follow requirements of compare method to return value less, equal or more than zero depending on comparison result.