Java中的priorityQueue顺序? [英] Order of priorityQueue in Java?

查看:616
本文介绍了Java中的priorityQueue顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解Java中 PriorityQueue 的顺序。因为我理解他们是基于堆,他们不能提供精确的迭代顺序作为插入顺序。我想知道那么在什么基础上priorityQueue排序自己。
给定代码:

I can't understand the order of PriorityQueue in Java. As i understand they are heap based and they can not provide exact iteration order as insertion order. I want to know then on what basis priorityQueue Sort themselves. Given code:

PriorityQueue<String> pq = new PriorityQueue<String>();
        pq.offer("hepqo");
        pq.offer("bro");
        pq.offer("wassup");
        pq.offer("okay");
        pq.offer("bingo");
        pq.offer("first");
        pq.offer("last");
        pq.offer("ssup");
        System.out.println("polled "+pq.poll());
        System.out.println(pq);
        String str[] = pq.toArray(new String[0]);
        Arrays.sort(str);
        for(String str1:str){
            System.out.println(str1);
        }

产生输出:

polledbingo
[bro, hepqo, first, okay, ssup, wassup, last]
bro
first
hepqo
last
okay
ssup
wassup

到数组,顺序将丢失。

我不能觉得这是由字符串自然秩序。

有没有办法维持优先级队列的插入顺序?

在什么基础上排序???

Even when i convert it to Array, the order is lost.
I can not feel this is even NATURAL ORDERING by String.
Is there any way to maintain the insertion order of priority Queues????
On what basis they sorted on???

推荐答案

队列根据字符串'字典顺序,这是它们的自然排序(即'b'在'f'之前,'f'在'h'之前等)。如果您希望队列维持插入顺序,请使用香草队列而不是 PriorityQueue

The queue is sorting according to the strings' lexicographic order, which is their natural ordering (i.e. 'b' precedes 'f', 'f' precedes 'h', etc). If you want the queue to maintain insertion order, then use a vanilla Queue instead of a PriorityQueue

这篇关于Java中的priorityQueue顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆