为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕标5832272 2021-11-03 16:08:23
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 回答

?
狐的传说

TA贡献1804条经验 获得超3个赞

根据文档,aPriorityQueue是:


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


通过查看源代码,我们可以在 backing 声明上方看到以下内容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())。


查看完整回答
反对 回复 2021-11-03
?
叮当猫咪

TA贡献1776条经验 获得超12个赞

还想补充一点,如果您希望队列结果按顺序排列,您可以轮询整个队列并将其清空。


    while (q2.size() > 0) {

        System.out.println(q2.poll());

    }

将打印出您期望的内容。


查看完整回答
反对 回复 2021-11-03
  • 2 回答
  • 0 关注
  • 196 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信