【问题标题】:Java PriorityQueue behaviour with 3 elements in the Queue [duplicate]队列中有 3 个元素的 Java PriorityQueue 行为[重复]
【发布时间】:2017-05-16 13:22:37
【问题描述】:

根据 PriorityQueue 的定义,它说:

优先级队列的元素按照它们的顺序排列 自然排序,或由队列构造时提供的比较器 时间,取决于使用的构造函数。

但是当我尝试使用队列中的 3 个元素时,这些元素似乎没有正确排序。

    Queue<Integer> q2 = new PriorityQueue<Integer>();
    q2.add(9);
    q2.add(7);
    q2.add(8);

    Iterator<Integer> i = q2.iterator();
    while(i.hasNext()){
        Integer e = i.next();
        System.out.println(e);
    }

输出:

7
9
8

[编辑] 如果元素个数为4,则排序似乎是正确的

    q2.add(9);
    q2.add(7);
    q2.add(8);
    q2.add(5);

    Iterator<Integer> i = q2.iterator();
    while(i.hasNext()){
        Integer e = i.next();
        System.out.println(e);
    }

输出:

5
7
8
9

【问题讨论】:

    标签: java priority-queue


    【解决方案1】:

    问题是您使用的是Iterator,它不保证在队列遍历期间的任何顺序。 PriorityQueue 的 Javadoc 说:

    方法iterator() 中提供的迭代器不能保证以任何特定顺序遍历优先级队列的元素。如果需要有序遍历,可以考虑使用Arrays.sort(pq.toArray())。

    当你轮询队列时,你会得到正确的顺序:

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

    【讨论】:

    • 为什么投反对票?这个答案有问题吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 2014-03-04
    • 2018-05-05
    • 1970-01-01
    • 2014-08-04
    相关资源
    最近更新 更多