问题
I am trying to use priority queue to keep an ordered list of integers. in a simple exaple like this:
PriorityQueue<Integer> queue = new PriorityQueue<>();
queue.offer(3000);
queue.offer(1999);
queue.offer(999);
for(Integer i : queue)
System.out.println(i);
This prints
999
3000
1999
This is not what I am expecting considering natural odering.
I simply want to iterate without removing or adding through the queue (which serves as a sorted list) WITH ordering. Can I still do that in a simple manner?
回答1:
PriorityQueue is a collection optimized for finding the tail or head value quickly, using a partially ordered tree structure called heap (look it up on wikipedia). If you pop the elements, they will be ordered. If you want to iterate, use for example a SortedSet instead, which also stores the elements sorted.
回答2:
This is a very sneaky problem with PriorityQueue: to quote the Api
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()).
Use Poll instead to get the head which will be in order
来源:https://stackoverflow.com/questions/10972459/strange-ordering-in-priorityqueue-in-java