作者peanut97 (花生)
看板java
标题[问题] 如何走访PriorityQueue但不移除元素?
时间Thu Mar 29 18:58:18 2012
查了好多资料,包括官方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
1F:推 eieio:试试用 clone() 复制出另一个 PriorityQueue,然後 poll()? 03/29 23:55
2F:→ adrianshum:我倒是看不明白你所谓 "新的array 不见了" 是什麽意思 03/30 07:33
3F:→ peanut97:谢谢eieio提供一种方法!! 03/30 23:53