简体   繁体   English

为什么我可以通过Iterator看到PriorityQueue元素,而不能通过poll看到?

[英]Why can I see PriorityQueue elements with an Iterator, but not with poll?

I have the following Java code, which creates a PriorityQueue and adds some elements to it: 我有以下Java代码,它将创建PriorityQueue并向其中添加一些元素:

public class Main {
    public static void main(String[] args) {
        PrintWriter out = new PrintWriter(System.out);
        PriorityQueue<Integer> q = new PriorityQueue<>();

        Integer[] integers = new Integer[10];
        Integer[] integers1 = new Integer[10];
        for (int i = 0; i < 10; i++) {
            integers[i] = i;
            integers1[i] = i + 10;
        }


        for (int i = 0; i < integers.length; i++) {
            q.add(integers[i]);
            q.add(integers1[i]);
        }

        out.println(q.size());

        for(int i = 0; i < integers.length; i++)
            out.println(q.poll());

        out.close();
    }    
}

In this code segment q.size() return the size of the queue, which is 20 . 在此代码段中, q.size()返回队列的大小,即20 However, when I retrieve elements using the poll() function in the last loop, it only retrieves the first 10 elements. 但是,当我在上一个循环中使用poll()函数检索元素时,它仅检索前10个元素。 However, when I use an Iterator to access the elements, it retrieves all the elements from the queue. 但是,当我使用Iterator访问元素时,它将从队列中检索所有元素。 It seems like the poll() method always retrieves half of the elements in the queue. 似乎poll()方法总是检索队列中一半的元素。

What's going on here? 这里发生了什么?

Your for loop has the wrong bounds here: 您的for循环在这里有错误的界限:

for(int i = 0; i < integers.length; i++)
    out.println(q.poll());

You've added integers.length + integers1.length elements to the priority queue, but you're only looping integers.length times. 您已经将integers.length + integers1.length元素添加到优先级队列中,但是只循环了integers.length次。 Try changing this to use a while loop: 尝试将其更改为使用while循环:

while (!q.isEmpty())
    out.println(q.poll());

Hope this helps! 希望这可以帮助!

You add 20 elements: 您添加20个元素:

                          10
                     _____________
                    /             \
for (int i = 0; i < integers.length; i++) {
    q.add(integers[i]);        \________________ x 2
    q.add(integers1[i]);       /
}

But you only retrieve 10 elements: 但是您只检索10个元素:

                          10
                     _____________
                    /             \
for(int i = 0; i < integers.length; i++)
    out.println(q.poll());    ------------  x 1

To drain the priority queue completely, do: 要完全耗尽优先级队列,请执行以下操作:

while (!q.isEmpty())
    out.println(q.poll());

因为integers.length等于10。这就是最后一个for语句的中断条件。

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

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