Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of priorityQueue in Java? [duplicate]

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?

like image 289
Sachin Verma Avatar asked Nov 03 '22 18:11

Sachin Verma


1 Answers

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

like image 164
Zim-Zam O'Pootertoot Avatar answered Nov 15 '22 05:11

Zim-Zam O'Pootertoot