Search code examples
javapriority-queue

How to create Priority Queue that sorts based on certain attribute of class?


I have created a Node class:

public class Node {
int vertex;
double latency;
Node predecessor;}

 public double getLatency()
{
    return latency;
}

I want to create a Priority Queue that sorts the Nodes by latency from least to greatest. After research, I believe I need to override the Comparator?

PriorityQueue<Node> pqueue = new PriorityQueue<Node>(numVertices, new Comparator<Node>({
        @Override

            ???
        }
    }

I'm not too sure how to override it.


Solution

  • The "???" in your example can be replaced with the following:

    public int compare(Node a, Node b) {
        if (a.getLatency() < b.getLatency())
            return -1;
        else if (a.getLatency() > b.getLatency())
            return 1;
        return 0;
    }