Search code examples
javaheappriority-queue

How does java know when in a PriorityQueue , an items key is changed in order to re-heapify the changed node


    class PQItem implements Comparable<PQItem>{
public int key;

public PQItem(int key) {
    this.key = key;

}

@Override
public int compareTo(PQItem o) {
    return this.key - o.key;
}

public String toString(){
    return this.key+"";
}

}

    PriorityQueue<PQItem> pq = new PriorityQueue<>();
    PQItem pq1 = new PQItem(45);
    PQItem pq2 = new PQItem(1);
    PQItem pq3 = new PQItem(4);
    PQItem pq4 = new PQItem(3);

    pq.offer(pq1);
    pq.offer(pq2);
    pq.offer(pq3);
    pq.offer(pq4);

    pq1.key = 40;
    pq2.key = -4;

    System.out.println(pq.poll());
    System.out.println(pq.poll());
    System.out.println(pq.poll());
    System.out.println(pq.poll());

Above prints as expected in sorted order -4 3 4 40

The question is I want to know if the operation of changing the key was done in O(lg n) with a Heapify on the changed node.If it was done, how does java detect me setting a property on one of the objects in order to trigger the heapify procedure on that node.


Solution

  • It doesn't, and it specifically says so in the Javadoc.

    The key changes you performed happened to be benign, as they didn't affect the ordering. You got lucky. Don't rely on it.