How to iterate over a PriorityQueue?

后端 未结 9 2057
被撕碎了的回忆
被撕碎了的回忆 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:22

    The peek() method does not remove anything from the queue, but because of this, it will continually get the top value until it IS empty. I'm guessing you checked if it was empty after your while loop, which would give you this conclusion.

    The only way to do this is to sort it yourself. You can get the original comparator for it like this:

    Event[] events = Arrays.sort(pq.toArray(), pq.comparator());
    for (Event e : events) {
        // do stuff
    }
    

提交回复
热议问题