0

I'm creating a Java PriorityQueue of Strings and naturally expecting the priority to follow lexicographic order. However, it doesn't seem to, can someone explain to me why this is the output [mackerel, trout, salmon] of the following code fragment:

java.util.PriorityQueue< String > q = new java.util.PriorityQueue<>();
q.offer( "salmon" );
q.offer( "trout" );
q.offer( "mackerel" );
System.out.println( q );

and not [mackerel, salmon, trout]? Thank you

Looked into the API and it said lexicographic order for Strings, but when ran the output is unexpected.

  • 1
    Does this answer your question? [The built-in iterator for java's PriorityQueue does not traverse the data structure in any particular order. Why?](https://stackoverflow.com/questions/2277430/the-built-in-iterator-for-javas-priorityqueue-does-not-traverse-the-data-struct) – Izruo May 19 '23 at 14:05

1 Answers1

2

The element order depicted by toString is based on how the elements are stored internally.

To see the elements in the order presented by the queue (i.e. according to their ordering), you need to remove each element (thereby taking the element off the head of the queue). The Javadocs explains this here:

The head of this queue is the least element with respect to their ordering

E.g.:

while (!q.isEmpty()) {
    System.out.println(q.remove());
}

which outputs the following:

mackerel
salmon
trout
jon hanson
  • 8,722
  • 2
  • 37
  • 61