编程语言
首页 > 编程语言> > 简单的Java PriorityQueue错误

简单的Java PriorityQueue错误

作者:互联网

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

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,aberdeen,而是能力.既然这是正确的字母顺序?

解决方法:

PriorityQueue.iterator()的文档:

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

这就是toString()用于构造字符串表示的内容,因为实现是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 (“[]”). […]

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

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

输出:

abc
aberdeen
ability

标签:java,priority-queue
来源: https://codeday.me/bug/20191008/1870487.html