我有使用 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());
}
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
[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
Run Code Online (Sandbox Code Playgroud)
大小为 10,那么为什么我无法使用 poll() 获取所有 10 个值?
for (int i = 0; i < pq.size(); i++) {
System.out.println(pq.poll());
}
Run Code Online (Sandbox Code Playgroud)
在每次循环迭代中,您将删除一个元素pq.poll(),该元素会递减pq.size(),并且您也会递增i。因此,在表达式中,i < pq.size()两个值彼此接近并在中间相遇,因此只循环一半次数。
相反,做:
while (!pq.isEmpty()) {
System.out.println(pq.poll());
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
121 次 |
| 最近记录: |