I meet a problem about order of PriorityQueue in Java 8, Intellij Idea, when I add the third number in the queue, the order is wrong, but only the third one have this probl
PriorityQueue's implementation is a priority heap implementation & not sorted list.
The Iterator provided in method iterator() is not guaranteed to traverse the elements of the priority queue in any specific order. If you need ordered traversal, use something like:
Arrays.sort(q.toArray());
for (Integer data :q) {
System.out.println(data);
}
The contract for PriorityQueue
does not guarantee iteration order, but rather it guarantees that each element removed from the priority queue will follow either the natural ordering of the queue's type, or the ordering of a custom comparator, should one be provided.
The Javadoc comments on what you are seeing:
Queues typically, but do not necessarily, order elements in a FIFO (first-in-first-out) manner. Among the exceptions are priority queues, which order elements according to a supplied comparator, or the elements' natural ordering, and LIFO queues (or stacks) which order the elements LIFO (last-in-first-out).
The contract which Java appears to enforce for priority queues is that the first element removed from the queue will follow the natural order of the object in the queue, or using a custom comparator, should one be provided.
If we add to your current script to remove the five elements added, we will see that the items returned will be ordered from least to greatest:
public static void main(String args[]) {
addNum(-1);
addNum(-2);
addNum(-3);
addNum(-4);
addNum(-5);
// now remove all elements
while (!q.isEmpty()) {
System.out.println(q.remove());
}
}
This prints:
-5
-4
-3
-2
-1
If you need a collection which maintains sorting order, then consider using something like TreeSet
. Or, you could use a regular ArrayList
, and then call Collections.sort()
if you want to impose a certain order.