有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java无法理解PriorityQueue如何更改排序顺序?

import java.util.*;
class abc {

    public static void main(String args[]){

        PriorityQueue<Integer> pq = new PriorityQueue<Integer>();

        pq.add(1);
        pq.add(2);
        pq.add(3);
        pq.add(4);
        pq.add(5);
        pq.add(6);

        System.out.println(pq);
        pq.remove();
        System.out.println(pq);     
    }           
}

当我移除元素时,顺序会改变。 根据字典排序,输出应按升序排列。但我得到的结果是:

output


共 (3) 个答案

  1. # 1 楼答案

    PriorityQueue实现一个堆数据结构。此数据结构具有使元素保持部分排序的属性。Heap是一个二叉树(即使实际上它是在数组中实现的),它保持以下不变性:如果节点P有一个子C,则P的值小于/大于C的值

    因此,只有第一个元素(根)保证是集合的最小值/最大值,而所有其他值仅部分排序

    为什么这么做?如果必须保留完整的排序集合,则插入/删除操作将采用O(n),而对于堆数据结构,它们都是O(log n)。如果您只对集合的max/min感兴趣,那么PriorityQueue比完整的排序数组有显著的优势

  2. # 2 楼答案

    ^{}toString()方法的文档中(将队列传递给System.out.println()方法时会调用该方法):

    The string representation consists of a list of the collection's elements in the order they are returned by its iterator, [...]

    ^{}iterator()方法的文档中:

    Returns an iterator over the elements in this queue. The iterator does not return the elements in any particular order.

    这就是你的答案

  3. # 3 楼答案

    调用System.out.println(pq);与调用System.out.println(pq.toString());相同

    如果你看一下documentation of the the toString() method,你会发现它说:

    Returns a string representation of this collection. The string representation consists of a list of the collection's elements in the order they are returned by its iterator, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (comma and space). Elements are converted to strings as by String.valueOf(Object).

    我强调了重要的部分。所以我们需要看一下documentation of the iterator of the priority queue,它表明:

    Returns an iterator over the elements in this queue. The iterator does not return the elements in any particular order.

    因此,代码的输出不允许对优先级队列施加的顺序得出任何结论

    main documentation of the PriorityQueue中写道:

    The Iterator provided in method iterator() is not guaranteed to traverse the elements of the priority queue in any particular order. If you need ordered traversal, consider using Arrays.sort(pq.toArray()).