java - 无法理解 PriorityQueue 如何改变排序顺序?

标签 java collections

import java.util.*;
class abc {

    public static void main(String args[]){

        PriorityQueue<Integer> pq = new PriorityQueue<Integer>();

        pq.add(1);
        pq.add(2);
        pq.add(3);
        pq.add(4);
        pq.add(5);
        pq.add(6);

        System.out.println(pq);
        pq.remove();
        System.out.println(pq);     
    }           
}

当我删除元素时,顺序会改变。 输出应根据字典排序按升序排列。但是我得到的输出是:

output

最佳答案

调用 System.out.println(pq); 等同于调用 System.out.println(pq.toString());

如果您查看 documentation of the the toString() method ,您会看到它指出:

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 ("[]"). Adjacent elements are separated by the characters ", " (comma and space). Elements are converted to strings as by String.valueOf(Object).

我突出了重要的部分。所以我们需要看看 documentation of the iterator of the priority queue其中指出:

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

因此您的代码的输出不允许对优先级队列强加的顺序作出任何结论。

main documentation of the PriorityQueue它说:

The Iterator provided in method iterator() is not guaranteed to traverse the elements of the priority queue in any particular order. If you need ordered traversal, consider using Arrays.sort(pq.toArray()).

关于java - 无法理解 PriorityQueue 如何改变排序顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44301081/

相关文章:

java - 如何从分布式环境访问位于 S3 存储桶中的 DBFS 文件?

java - 如何在 spring boot standalone app 中激活 JMX 监控

java - 将二进制字符串转换为十六进制字符串JAVA

java - 在 Java 中找不到方法 "setString(int,String)"的符号

java - RandomAccess 接口(interface),为什么没有方法?

java - 来自 Collections.unmodifiableMap get() 的 StackOverflowError?

java - < 的用途是什么?延伸 E >

Java 迭代器类 - 无法解析符号 "E"

java - 在 Java 中如何查找两个列表的相似程度?

javascript - Typescript 跨项目共享原始类型的自定义方法