PriorityQueue not sorting on add

I guess you expect PriorityQueue to return elements in particular order when you iterate it. However, PriorityQueue doesn’t provide such a behaviour, because it’s implemented as a priority heap rather than sorted list. From javadoc:

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

The only guarantee provided by PriorityQueue is that poll(), peek(), etc return the least element. If you need ordered iteration of elements, use some other collection such as TreeSet.

Leave a Comment