当前位置: 动力学知识库 > 问答 > 编程问答 >

java - PriorityQueue iterating only half the elements

问题描述:

I have program which uses PriorityQueue. poll() is not giving all the values in the queue.

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()?

网友答案:

On each loop iteration you are removing an element, so pq.size() is decremented, and incrementing i, so in the expression i < pq.size() the values approach each other and meet in the middle, which means it only loops 5 times.

Instead do:

while (!pq.isEmpty()) {
    System.out.println(pq.poll());
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: