Search code examples
javapriority-queue

What is the standard behavior of the PriorityQueue class?


so i'm trying to build my first prim algorithm, and for that i am sorting the edges by priority trought it's weight.

So i figured would be helpfull if i use a Priority Queue, and for that i need to make my edge implements the Comparable<> Interface, so i did but i don't know what does the priority queue considers as highest priority, would it be the heaviest or the lightest edge? And also, will the Priority queue add the same object twice, or will it behave as a Set ?

Here is my code:

Public class Edge implements Comparable<Edge> {
   int weight;

   public int compareTo(Edge e) {
      return e.getWeight() - this.weight;
   }
}

I expect to receive the lightest edge as the highest priority. Worth noting that is my first time implementing a Priority Queue and comparable


Solution

  • A priority queue uses what is called the Natural Ordering of your objects. The compareTo() method needs to return a -1, 0 1. The object with the highest priority will always be at the front of the queue.

    I would change your compareTo implementation too something that operates like this.

    public int compareTo(Edge e) 
    {
        if( e.getWeight() > this.weight )
            return 1;
        else if( e.getWeight() == this.weight )
            return 0;
        else //e.getWeight() < this.weight
            return -1
    }