简体   繁体   English

PriorityQueue 只迭代一半的元素

[英]PriorityQueue iterating only half the elements

I have program which uses PriorityQueue.我有使用 PriorityQueue 的程序。 poll() is not giving all the values in the queue. poll() 没有给出队列中的所有值。

class Coffee {
    public static void main(String[] args) {
        PriorityQueue<Double> pq = new PriorityQueue<Double>();
        Random rand = new Random();
        for (int i = 0; i < 10; i++) {
            pq.offer(rand.nextDouble());
        }

        System.out.println(pq);
        System.out.print("size value " + pq.size());

        for (int i = 0; i < pq.size(); i++) {
            System.out.println(pq.poll());
        }
    }
}

Output:输出:

[0.005756373546009885, 0.057563473207216886, 0.3415582636412481, 0.2026760924302
6186, 0.10792479235868724, 0.768845643547834, 0.5107848139799113, 0.758559713387
8311, 0.6437353209123445, 0.5156937257761389]
size value 10
0.005756373546009885
0.057563473207216886
0.10792479235868724
0.20267609243026186
0.3415582636412481

The size is 10, so why am I not getting all the 10 values with poll()?大小是 10,那么为什么我没有通过 poll() 获得所有 10 个值?

for (int i = 0; i < pq.size(); i++) {
    System.out.println(pq.poll());
}

On each loop iteration you are removing an element by pq.poll() , which decrements pq.size() , and you are also incrementing i .在每次循环迭代中,您都会通过pq.poll()删除一个元素,这会减少pq.size() ,并且您也会增加i So in the expression i < pq.size() the two values approach each other and meet in the middle, so it only loops half the times.所以在表达式i < pq.size() ,两个值彼此接近并在中间相遇,所以它只循环了一半。

Instead do:而是这样做:

while (!pq.isEmpty()) {
    System.out.println(pq.poll());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM