Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How PriorityQueue in Java sorts duplicate entries?

It may sound silly, but it makes sense when you have object of (key, value) pair and you sort them according to the keys. To illustrate my point with code:

public class Pair implements Comparable<Pair> {
    private int value;
    private int key;

    public Pair(int key, int value) {
        this.key   = key;
        this.value = value;
    }

    @Override
    public int compareTo(Pair o) {
        if (this.key > o.key)
            return 1;
        else if (this.key < o.key)
            return -1;
        return 0;
    }
}

public class program {
    public static void main(String[] args) {
        PriorityQueue<Pair> queue = new PriorityQueue<Pair>;
        queue.add(new Pair(1,1));
        queue.add(new Pair(1,2));
        queue.add(new Pair(1,3));

        Pair pair = queue.poll(); // What would be in pair?
    }
}

What would be in pair? The first or the last added element? Or any of them without possibility to decide?

like image 834
Petr Avatar asked Feb 06 '13 07:02

Petr


1 Answers

PriorityQueue API makes no promises for this situation:

The head of this queue is the least element with respect to the specified ordering. If multiple elements are tied for least value, the head is one of those elements -- ties are broken arbitrarily. The queue retrieval operations poll, remove, peek, and element access the element at the head of the queue.

But it's easy to test. Add toString to Pair

@Override
public String toString() {
    return key + " " + value;
}

and print the poll result

    Pair pair = queue.poll(); // What would be in pair?
    System.out.println(pair);

it prints

1 1
like image 104
Evgeniy Dorofeev Avatar answered Sep 21 '22 06:09

Evgeniy Dorofeev