【问题标题】:Queue not ordering naturally [duplicate]队列不自然排序[重复]
【发布时间】:2012-11-20 01:25:52
【问题描述】:

可能重复:
Why is this strange order happens in PriorityQueue in java?

请看下面的代码:

public static void main(String[] args) {
    Queue<String> q = new PriorityQueue<String>();
    q.offer("car");
    q.offer("airplane");
    q.offer("bicycle");
    Iterator<String> i = q.iterator();
    while(i.hasNext())
        System.out.print(i.next() + " ");
}

谁能解释一下为什么输出是这样的

airplane car bicycle

而不是

airplane bicycle car

?

由于in the API 它表示优先级队列的元素根据其自然顺序进行排序。

【问题讨论】:

标签: java queue priority-queue


【解决方案1】:

根据javadoc for the iterator

迭代器不会以任何特定顺序返回元素。

但是,第一个项目(头部)保证是最小的。所以这应该打印出你所期望的:

public static void main(String[] args) throws Exception {
    Queue<String> q = new PriorityQueue<String>();
    q.offer("car");
    q.offer("airplane");
    q.offer("bicycle");
    String e = null;
    while ((e = q.poll()) != null) {
        System.out.println(e);
    }
}

如果要对迭代进行排序,则需要使用不同的结构,例如,如果没有重复,则使用 TreeSet

【讨论】:

  • @Lang 这可能不是随机的 - 我没有查看实现,但是当您插入一个新项目时可能发生的情况是它小于头部并首先插入,或者,如果不是,则将其放在尾部。这可以解释你看到的顺序。
  • 但是为什么我总是得到相同的随机顺序?迭代器出了点问题。
  • (对不起,我的问题在你的回答之后结束了)
【解决方案2】:

PriorityQueue 基于优先级堆。尽管元素没有排序,但这种数据结构允许非常快速地检索最少的元素。向 PriorityQueue 添加元素比向基于树的 TreeSet 添加元素要快。由于元素未排序,因此正如 API 所说,迭代器“不会以任何特定顺序返回元素”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-29
    • 2010-11-22
    • 2012-01-24
    • 1970-01-01
    • 2016-11-07
    • 1970-01-01
    • 1970-01-01
    • 2019-02-21
    相关资源
    最近更新 更多