This week's book giveaway is in the Agile and Other Processes forum. We're giving away four copies of Darcy DeClute's Scrum Master Certification Guide: The Definitive Resource for Passing the CSM and PSM Exams and have Darcy DeClute on-line! See this thread for details.
Java API wrote:
The Iterator provided in method iterator() is not guaranteed to traverse the elements of the PriorityQueue in any particular order. If you need ordered traversal, consider using Arrays.sort(pq.toArray()).
Are you sure you understand what's going on? Because the answer, as it relates to the question, is a little confusing.
PriorityQueue is a sorted collection. If you instantiate a PriorityQueue without using a Comparator, then the sort order is established by the compareTo() method (which all elements inserted to the PriorityQueue must implement.) You can also use a Comparator by using the appropriate PriorityQueue constructor. In the case of String, which is the case in your example, String implements Comparable<String>, which will cause lexicographical ordering.
But: PriorityQueue inherits iterator() from Collection, and that method returns an Iterator which doesn't guarantee any specific ordering. Therefore, your second line of output is a fluke (you shouldn't rely on that order.) However, if you polled the queue sequentially, you would get the elements in the lexicographical sorted order in a reliable way.
All code in my posts, unless a source is explicitly mentioned, is my own.