gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 06:28:44 27 4
gpt4 key购买 nike

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/

27 4 0
文章推荐: mysql - 如何使用 mySQL 或 Cassandra 查询获取包含相同值的间隔?
文章推荐: mysql - 调用存储过程后MySQL存储过程的OUT参数为空
文章推荐: mysql - 更正 sum 函数语法错误中的子查询
文章推荐: java - 使用 java 流将 Stream 转换为 List