0

For this:

    PriorityQueue<Integer> pq = new PriorityQueue<>();
    pq.add(2);
    System.out.println(pq);
    pq.add(4);
    System.out.println(pq);
    pq.add(1);
    System.out.println(pq);

I am getting this output:

[2]
[2, 4]
[1, 4, 2]

Why is the output for the third line not [2,4,1] ?

bucky
  • 392
  • 4
  • 18

1 Answers1

2

Nowhere it's written that the toString implementation for PriorityQueue returns them in order. Actually the problem is that:

  • PriorityQueue doesn't provide a toString() implementation, so AbstractCollection::toString() is used.
  • AbstractCollection::toString() prints items by using iterator() method (so by calling next() and hasNext())
  • the documentation about PriorityQueue::iterator states: Returns an iterator over the elements in this queue. The iterator does not return the elements in any particular order.

So basically toString relies on iterator() which doesn't provide an ordered view of the elements.

Jack
  • 131,802
  • 30
  • 241
  • 343