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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With