具有比较器实现的Java PriorityQueue不返回字符串的相反顺序

时间:2018-10-07 19:03:11

标签: java collections priority-queue

PriorityQueue<String> q2=new PriorityQueue<String> (15, new Comparator<String>() {

        @Override
        public int compare(String o1, String o2) {
            //System.out.println(o1+" -- "+o2);
            return o2.compareTo(o1);
        }
    });
        //System.out.println(q2.peek());
            //q2.offer("s");
            q2.offer("A");
            q2.offer("L");
            q2.offer("Z");
            q2.offer("J");
            q2.offer("X");
        System.out.println(q2);

以上代码的输出为[Z,X,L,A,J] 而不是[Z,X,L,J,A] 我无法弄清楚我的代码出了什么问题

2 个答案:

答案 0 :(得分:1)

根据documentationPriorityQueue为:

  

基于优先级堆的无界优先级队列。

通过查看源代码,我们可以在支持Object[]的声明上方看到以下内容:

/**
 * Priority queue represented as a balanced binary heap: the two
 * children of queue[n] are queue[2*n+1] and queue[2*(n+1)].  The
 * priority queue is ordered by comparator, or by the elements'
 * natural ordering, if comparator is null: For each node n in the
 * heap and each descendant d of n, n <= d.  The element with the
 * lowest value is in queue[0], assuming the queue is nonempty.
 */

因此,迭代顺序将不是您期望的。

文档还指出:

  

不保证方法iterator()中提供的Iterator和方法spliterator()中提供的Spliterator以任何特定顺序遍历优先级队列的元素。如果需要顺序遍历,请考虑使用Arrays.sort(pq.toArray())。

答案 1 :(得分:0)

还想补充一点,如果您想要队列结果以便可以轮询整个队列并将其清空。

    while (q2.size() > 0) {
        System.out.println(q2.poll());
    }

将打印出您的期望。