gpt4 book ai didi

java - 如何理解PriorityQueue?

转载 作者:行者123 更新时间:2023-12-01 07:52:38 24 4
gpt4 key购买 nike

这是我的代码

 import java.util.*;
public class PriorityPuzzle{
public static void main(String []args){
PriorityQueue<Integer> prq = new PriorityQueue<Integer>();
for ( int i = 10; i > 0; i-- ){
prq.add (i);
System.out.print(i+" , ");
}

System.out.println ( "\n Initial priority queue values are: "+ prq);
}
}

结果

enter image description here

我不知道为什么队列的优先级变成{1,2,5,4,3,9,6,10,7,8}

最佳答案

toString() method for PriorityQueue只是继承the one from AbstractCollection 。这只是迭代集合中的项目并打印它们。

来自文档 for the iterator of 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/34823958/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com