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

看板java作者 ( )時間12年前 (2012/03/29 20:35), 編輯推噓2(200)
留言2則, 1人參與, 最新討論串2/2 (看更多)
※ 引述《peanut97 (花生)》之銘言: : 查了好多資料,包括官方API、google網頁,都沒有看這樣的問題... : 我想請問: : 想要把PriorityQueue裡面的內容依優先順序印出來檢查一下, : 但不要把裡面的元素移除,該怎麼做? The Iterator provided in method 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()). 所以一般印 collections 的方式都沒有辦法照你要的順序印,因為那些方式都是透過 Iterator 來實作的功能。看 PriorityQueue 的 source code,其實會發現它裡面其實是 用一個 array 來存物件,只有在用到任何 Queue 的 method 時,他才會去依照 comparator 或 natural order 來調整 array。 至於 Arrays.sort(pq.toArray())的意思是,因為你沒有辦法透過 iterator 來看, 所以建議你直接把內容copy一份出來,然後再用 Arrays.sort() 排序過後看。 要實作的話,code 大概是這種樣子 PriorityQueue<Integer> pq = new PriorityQueue<Integer>(); for (int x : new int[] {9, 5, 3, 7, 6, 1, 8}) { pq.add(x); } Object[] array = pq.toArray(); Arrays.sort(array); System.out.println(Arrays.toString(array)); : 誠心請教各位前輩... : 該怎麼檢查目前的priorityQueue的元素順序? : 以及官方API中,Arrays.sort(pq.toArray())這個奇怪寫法是什麼意思? -- We who cut mere stones must always be envisioning cathedrals. -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 114.27.164.94 ※ 編輯: awert 來自: 114.27.164.94 (03/29 20:39)

03/30 13:39, , 1F
謝謝您 原來要先把queue的東西弄成array後再排序 才看得
03/30 13:39, 1F

03/30 13:50, , 2F
03/30 13:50, 2F
文章代碼(AID): #1FT5SGsk (java)
文章代碼(AID): #1FT5SGsk (java)