[問題] 如何走訪PriorityQueue但不移除元素?

看板java作者 (花生)時間12年前 (2012/03/29 18:58), 編輯推噓1(102)
留言3則, 3人參與, 最新討論串1/2 (看更多)
查了好多資料,包括官方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
試試用 clone() 複製出另一個 PriorityQueue,然後 poll()?
03/29 23:55, 1F

03/30 07:33, , 2F
我倒是看不明白你所謂 "新的array 不見了" 是什麼意思
03/30 07:33, 2F

03/30 23:53, , 3F
謝謝eieio提供一種方法!!
03/30 23:53, 3F
文章代碼(AID): #1FT41CgY (java)
文章代碼(AID): #1FT41CgY (java)