PriorityQueue只迭代一半元素

时间:2014-08-24 13:49:34

标签: java

我有使用PriorityQueue的程序。 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());
        }
    }
}

输出:

[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

大小是10,那么为什么我没有使用poll()得到所有10个值?

1 个答案:

答案 0 :(得分:3)

在每次循环迭代中,您要移除一个元素,因此pq.size()递减,并递增i,因此在表达式i < pq.size()中,值彼此接近并在中间相遇,这意味着它只循环5次。

取而代之的是:

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