简单Java PriorityQueue< String>错误 [英] Simple Java PriorityQueue<String> error

查看:49
本文介绍了简单Java PriorityQueue< String>错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要做的就是将三个字符串添加到Java PriorityQueue中,然后将它们打印出来这是我的代码:

All I am doing is add three strings to a Java PriorityQueue and then print them out This is my code:

import java.util.*;
import java.lang.*;

class Main
{
    public static void main (String[] args) throws java.lang.Exception
    {
        PriorityQueue<String> pq=new PriorityQueue<String>();
        pq.add("abc");
        pq.add("ability");
        pq.add("aberdeen");

        String s="ability";
        System.out.println(s.compareTo("aberdeen"));

        System.out.println(pq);
    }
}

这是输出:

4
[abc, ability, aberdeen]

这不是应该是 abc,阿伯丁,能力.因为那是正确的字母顺序?

Shouldn't this be abc, aberdeen, ability instead. since that's the correct alphabetic order?

推荐答案

来自

返回此队列中元素的迭代器.迭代器不会以任何特定顺序返回元素.

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

这就是 toString()用来构造字符串表示形式的原因,因为实现是

That's what toString() is using to construct the string representation, as the implementation is inherited from AbstractCollection:

返回此集合的字符串表示形式.字符串表示形式包含一个集合元素的列表,这些元素按其迭代器返回的顺序排列,并括在方括号("[]")中.[...]

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 ("[]"). [...]

尝试将结果出队,您将获得预期的顺序:

Try dequeuing the results instead, and you'll get the expected order:

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

输出:

abc
aberdeen
ability

这篇关于简单Java PriorityQueue&lt; String&gt;错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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