Search code examples
javacompareheapsort

Understanding how the override works with compareTo in a Java priority queue?


I'm making a custom priority queue where I essentially push objects to a PQ and sort by a specific key in that object:

Priority Queue Entry Class

package Graphs;

public class PQEntry implements Comparable<PQEntry> {
    public int node;
    public int nodeVal;

    public PQEntry(int node, int nodeVal) {
        this.node = node;
        this.nodeVal = nodeVal;
    }

    @Override
    public String toString() {
        return "Node: " + this.node + ", Value: " + this.nodeVal;
    }

    public int getNodeVal() {
        return this.nodeVal;
    }

    @Override
    public int compareTo(PQEntry other) {
        return Integer.compare(this.getNodeVal(), other.nodeVal);
    }
}

Now, everything is fine and dandy, the priority works as it should:

PriorityQueue<PQEntry> pq = new PriorityQueue();

But I am new to Java and I am confused as to how/where/when the compareTo in my PQEntry class gets applied to the PriorityQueue class and how this is exactly working.

When I call the add function inside PriorityQueue does it initiate some swapping algorithm calling a super method from my PQEntry class? I'm really a bit new to Java and trying to understand the process flow here.


Solution

  • I'll try to clarify things for you.

    In the documentation of PriorityQueue you'll notice it states:

    The elements of the priority queue are ordered according to their natural ordering, or by a Comparator provided at queue construction time, depending on which constructor is used. A priority queue does not permit null elements. A priority queue relying on natural ordering also does not permit insertion of non-comparable objects (doing so may result in ClassCastException).

    The PriorityQueue expects either a Comparator or Comparable objects. As long as one of these is provided the queue will "work as it should" because it simply relies on those interfaces.

    When a comparator is not provided PriorityQueue will try to cast elements as Comparable and then use the compareTo method to determine how to sort them.

    When a comparator is provided PriorityQueue will simply use that object to perform the comparison of elements and sort them accordingly.

    For further reading you can look at the Java Tutorials, in particular the lesson on Interfaces and Inheritance.