I can't understand the order of PriorityQueue
in Java. As i understand they are heap based and they can not provide exact iteration order as insertion order. I want to know then on what basis priorityQueue Sort themselves.
Given code:
PriorityQueue<String> pq = new PriorityQueue<String>();
pq.offer("hepqo");
pq.offer("bro");
pq.offer("wassup");
pq.offer("okay");
pq.offer("bingo");
pq.offer("first");
pq.offer("last");
pq.offer("ssup");
System.out.println("polled "+pq.poll());
System.out.println(pq);
String str[] = pq.toArray(new String[0]);
Arrays.sort(str);
for(String str1:str){
System.out.println(str1);
}
produces output:
polledbingo
[bro, hepqo, first, okay, ssup, wassup, last]
bro
first
hepqo
last
okay
ssup
wassup
Even when i convert it to Array, the order is lost.
I can not feel this is even NATURAL ORDERING by String.
Is there any way to maintain the insertion order of priority Queues?
On what basis they sorted on?
The queue is sorting according to the strings' lexicographic order, which is their natural ordering (i.e. 'b' precedes 'f', 'f' precedes 'h', etc). If you want the queue to maintain insertion order, then use a vanilla Queue
instead of a PriorityQueue
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