0

Here is My Code

 import java.util.*;
    public class PriorityPuzzle{
        public static void main(String []args){
            PriorityQueue<Integer> prq = new PriorityQueue<Integer>();  
            for ( int i = 10; i > 0; i-- ){  
                  prq.add (i); 
                  System.out.print(i+" , ");
            }  

            System.out.println ( "\n Initial priority queue values are: "+ prq);    
        }  
    }

Result

enter image description here

I donnot know why the after Priority the queue become {1,2,5,4,3,9,6,10,7,8}

Sheldon
  • 519
  • 8
  • 20

2 Answers2

3

The docs say that this priority queue is based on a priority heap. The docs also don't mention that toString() is overridden by this class. PriorityQueue actually uses the toString method from AbstractCollection.

I'm going to guess that therefore toString() doesn't bother to print the elements in order, it just uses some arbitrary internal order dependent on the heap. If you want to print the elements in order, you'll have to use an Iterator or something similar and print them yourself.

markspace
  • 10,621
  • 3
  • 25
  • 39
  • 3
    Iterating won't work, either. From the docs: "The Iterator provided in method iterator() is not guaranteed to traverse the elements of the priority queue in any particular order. If you need ordered traversal, consider using Arrays.sort(pq.toArray())." – yshavit Jan 16 '16 at 05:57
  • Seriously? Crap, I should read the docs myself. Thanks for the pointer. – markspace Jan 16 '16 at 05:58
  • I wonder what is logical that sort from 10,9,8,7,6,5,4,3,2,1 to 1,2,5,4,3,9,6,10,7,8 – Sheldon Jan 16 '16 at 06:02
  • 1
    @Sheldon It's not logical, it's *arbitrary*. See yshavit's comment and augray's answer. Also, read the docs (unlike me). – markspace Jan 16 '16 at 06:05
3

The toString() method for PriorityQueue just inherits the one from AbstractCollection. This just iterates over the items in the collection and prints them.

From the docs for the iterator of PriorityQueue:

The Iterator provided in method iterator() is not guaranteed to traverse the elements of the priority queue in any particular order. If you need ordered traversal, consider using Arrays.sort(pq.toArray()).

So printing the queue doesn't print the items in the order that you would get them if you retrieved them from the queue one at a time.

augray
  • 3,043
  • 1
  • 17
  • 30
  • I wonder what is logical that sort from 10,9,8,7,6,5,4,3,2,1 to 1,2,5,4,3,9,6,10,7,8 – Sheldon Jan 16 '16 at 06:02
  • Apparently, according to the docs and markspace, the Java `PriorityQueue` is based on a [heap](https://en.wikipedia.org/wiki/Heap_(data_structure)). – augray Jan 16 '16 at 06:07