【问题标题】:Why is this strange order happens in PriorityQueue in java? [duplicate]为什么这个奇怪的顺序发生在 java 的 PriorityQueue 中? [复制]
【发布时间】:2012-09-04 08:29:08
【问题描述】:

我阅读了有关 PriorityQueue 的文档和我能找到的所有内容,但仍然不明白为什么输出如此奇怪我的意思是我无法理解添加顺序,谁能解释一下?

PriorityQueue<String> pq = new PriorityQueue<String>();
pq.offer("2"); 
System.out.println("add 2 : " + pq); 
pq.offer("4");
System.out.println("add 4 : " + pq);
System.out.println(pq.peek() + " ");
pq.offer("1");
System.out.println("offer 1 : " + pq);
pq.offer("3");
System.out.println("add 3 : " + pq);
pq.remove("1");
System.out.println("remove 1 : " + pq);

输出:

add 2 : [2]
add 4 : [2, 4]            <- why 4 goes there
offer 1 : [1, 4, 2]       <- why 1 goes first
add 3 : [1, 3, 2, 4]      <- why reorder
remove 1 : [2, 3, 4]      <- again

【问题讨论】:

  • 元素在heap order.
  • 需要考虑的是PriorityQueue 是否实现toString,它对String 中的值进行排序。由于toString 似乎在AbstractCollection 中实现,我建议它可能不会。尝试使用poll 以正确的顺序取出元素。
  • @JohnB 来自 AbstractCollection:“字符串表示由集合元素的列表组成,按其迭代器返回的顺序排列,括在方括号 ("[]") 中。”如果 PriorityQueue 本身没有覆盖该方法,那么应该保证它是有序的(尽管不一定是您所期望的)。
  • @AnthonyGrist:“迭代器不会以任何特定顺序返回元素。” docs.oracle.com/javase/6/docs/api/java/util/…

标签: java algorithm data-structures collections


【解决方案1】:

PriorityQueue 是一个树状结构,可确保第一个元素是最小的。其他元素的顺序并不重要,很可能是由于 PQ 如何平衡树。

正如@larsmans 指出的那样,这被称为最小堆顺序

【讨论】:

    【解决方案2】:

    PriorityQueue 只保证第一个元素是最小的。

    binary heap 只保证每个子堆(子树)中的根是最小的元素。
    堆实际上是一个完整的树(或它的数组表示)。每当您插入违反条件的元素(小于根)时,旧的根就会被筛选掉。这是在堆上递归完成的。

    这种部分排序允许快速且相对缓存效率较高(使用数组表示)的数据结构,如果您只需要每个时间点的 min 元素,就可以使用这种数据结构。

    【讨论】:

      【解决方案3】:

      Java 文档:

      An unbounded priority queue based on a priority heap. 
      The elements of the priority queue are ordered according to their natural ordering, or by a Comparator provided at queue construction time, depending on which constructor is used. 
      A priority queue does not permit null elements. 
      A priority queue relying on natural ordering also does not permit insertion of 
      non-comparable objects (doing so may result in ClassCastException).
      

      还说:

      The head of this queue is the least element with respect to the specified ordering. If multiple elements are tied for least value, the head is one of those elements -- ties are broken arbitrarily. The queue retrieval operations poll, remove, peek, and element access the element at the head of the queue.
      

      您输出的是toString() 方法。输出是由于该方法如何迭代树。与Iterator的顺序相同。

      【讨论】:

        猜你喜欢
        • 2013-07-15
        • 1970-01-01
        • 2012-04-29
        • 1970-01-01
        • 2012-05-21
        • 1970-01-01
        • 2019-10-19
        • 1970-01-01
        • 2021-11-04
        相关资源
        最近更新 更多