Strange ordering in PriorityQueue in Java [duplicate]

倖福魔咒の 提交于 2019-12-10 10:50:40

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!