Search code examples
javapriority-queue

Why does toString of PriorityQueue returns elements out of order?


I have this simple code using PriorityQueue where I want integers to be stored in decreasing order.

PriorityQueue<Integer> jumps = new PriorityQueue<>(20,Collections.reverseOrder());
jumps.add(8);
jumps.add(5);
jumps.add(15);
jumps.add(2);
jumps.add(16);
System.out.println(jumps.toString());

This prints

[16, 15, 8, 2, 5]

while I would have expected

[16, 15, 8, 5, 2]

What am I doing wrong here ?


Solution

  • The order returned by the Iterator of a PriorityQueue is not guaranteed (emphasis theirs):

    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()).

    This is what toString() uses, therefore the order of the elements in the toString() output is also not specified

    What is guaranteed is that multiple calls to poll() will return the values in the appropriate order:

    while (!jumps.isEmpty()) {
      System.out.println(jumps.poll());
    }