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

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] 我不知道我的代码有什么问题


慕标5832272
浏览 197回答 2
2回答

狐的传说

根据文档,aPriorityQueue是:基于优先级堆的无界优先级队列。通过查看源代码,我们可以在 backing 声明上方看到以下内容Object[]:/**&nbsp;* Priority queue represented as a balanced binary heap: the two&nbsp;* children of queue[n] are queue[2*n+1] and queue[2*(n+1)].&nbsp; The&nbsp;* priority queue is ordered by comparator, or by the elements'&nbsp;* natural ordering, if comparator is null: For each node n in the&nbsp;* heap and each descendant d of n, n <= d.&nbsp; The element with the&nbsp;* lowest value is in queue[0], assuming the queue is nonempty.&nbsp;*/因此,迭代顺序不会是您所期望的。该文件还指出:方法 iterator() 中提供的 Iterator 和方法 spliterator() 中提供的 Spliterator 不能保证以任何特定顺序遍历优先级队列的元素。如果您需要有序遍历,请考虑使用 Arrays.sort(pq.toArray())。

叮当猫咪

还想补充一点,如果您希望队列结果按顺序排列,您可以轮询整个队列并将其清空。&nbsp; &nbsp; while (q2.size() > 0) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(q2.poll());&nbsp; &nbsp; }将打印出您期望的内容。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java