How to iterate over a PriorityQueue?

后端 未结 9 2056
被撕碎了的回忆
被撕碎了的回忆 2020-11-30 03:48
for (Event e : pq)

doesn\'t iterate in the priority order.

while(!pq.isEmpty()){
  Event e = pq.poll();
}

This wo

9条回答
  •  一整个雨季
    2020-11-30 04:25

    So taking the priorityQueue in a List and then sorting it is a good option as mentioned above. Here are some details why the iterator gives unexpected results:

    The iterator does not return elements in the correct order because it prints from the underlying data structure (similar to ArrayList). The ArrayList has data stored in it in the same way the data is stored in an Array implementation of BinaryHeap. For example:

    PriorityQueue pq = new PriorityQueue<>();
    ArrayList test = new ArrayList(Arrays.asList(6,12,7,9,2));
    test.forEach(x -> pq.add(x)); 
    System.out.println("Priority Queue:- "+pq); [2, 6, 7, 12, 9]
    

    where childOf(i) is 2*i+1 and 2*i+2 and parentOf(i) is (i-1)/2

提交回复
热议问题