[問題] 如何走訪PriorityQueue但不移除元素?
查了好多資料,包括官方API、google網頁,都沒有看這樣的問題...
我想請問:
想要把PriorityQueue裡面的內容依優先順序印出來檢查一下,
但不要把裡面的元素移除,該怎麼做?
理由是我自己寫Comparator,想debug一下,看看某狀態時的PriorityQueue是不是和我想
的一樣的順序
一般的PriorityQueue使用方式如下:
import java.util.*;
public class Test {
public static void main(String[] args) {
PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
for (int x : new int[] { 9, 5, 3, 7, 6, 1, 8}) {
pq.add(x);
}
Integer n = null;
while ((n = pq.poll()) != null) {
System.out.print(n);
}
}
}
他使用poll()函數來列出元素,但這樣元素就被移除了。
官方API說:
<中文版>
此類別及其迭代器實作了 Collection 和 Iterator 介面的所有可選 方法。方法
iterator() 中提供的迭代器不 保證以任何特定的順序遍歷優先級佇列中的元素。如果
需要按順序遍歷,請考慮使用 Arrays.sort(pq.toArray())。
<英文版>
This class and its iterator implement all of the optional methods of the
Collection and Iterator interfaces. 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()).
很奇怪的用法。
pq.toArray() 這個函數會傳回一個"新的array",再把這個新的array丟進Arrays.sort函
數裡
sort完,那個"新的array"就不見了啊...@@囧
誠心請教各位前輩...
該怎麼檢查目前的priorityQueue的元素順序?
以及官方API中,Arrays.sort(pq.toArray())這個奇怪寫法是什麼意思?
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.113.69.9
推
03/29 23:55, , 1F
03/29 23:55, 1F
→
03/30 07:33, , 2F
03/30 07:33, 2F
→
03/30 23:53, , 3F
03/30 23:53, 3F
討論串 (同標題文章)
以下文章回應了本文:
完整討論串 (本文為第 1 之 2 篇):