How does PriorityQueue in Java sort duplicate records?

This may seem silly, but it makes sense when you have an object (key, value) and you sort them by keys. To illustrate your 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 will be in pair ? The first or last item added? Or any of them without the ability to solve?

+6
source share
2 answers

PriorityQueue API does not make promises for this situation:

The head of this queue is the smallest element relative to the specified order. If several elements are attached to the smallest value, the head is one of these elements - the bonds break arbitrarily. Queue search, delete, view, and item access the item at the head of the queue.

But this is easy to verify. Add toString to Pair

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

and print the survey results

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

he prints

 1 1 
+7
source

Basically a Queue is the structure of firstInfirstOut.

In PriorityQueue , a comparable value defines the order.

Like your case priority, all Pair() same. hence no change in order.

First-In-First-Out ie Pairs (1,1) (1,2) (1,3)

According to the documentation

Poll, retrieve, view, and access the search item in the queue of the item at the beginning of the queue.

-3
source

All Articles