Queue not ordering naturally [duplicate]

青春壹個敷衍的年華 提交于 2019-12-01 19:01:48

PriorityQueue is based on a priority heap. This data structure allows to retrieve the least element very quickly though the elements are not sorted. Adding elements to PriorityQueue is faster than to TreeSet which is tree based. Since the elements are not sorted, the iterator, as API says, "does not return the elements in any particular order".

According to the javadoc for the iterator:

The iterator does not return the elements in any particular order.

However, the first item (head) is guaranteed to be the smallest. So this should print what you expect:

public static void main(String[] args) throws Exception {
    Queue<String> q = new PriorityQueue<String>();
    q.offer("car");
    q.offer("airplane");
    q.offer("bicycle");
    String e = null;
    while ((e = q.poll()) != null) {
        System.out.println(e);
    }
}

If you want iteration to be sorted, you need to use a different structure, for example a TreeSet if you don't have duplicates.

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