The order of the PriorityQueue is wrong

前端 未结 2 968
清酒与你
清酒与你 2021-01-20 05:47

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

2条回答
  •  离开以前
    2021-01-20 06:22

    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);
    }
    

提交回复
热议问题