删除PriorityQueue的顶部?
问题描述:
假设我使用Java.util中的PriorityQueue类。我想从PriorityQueue pq中删除最大的数字,我们假设它位于队列的头部。删除PriorityQueue的顶部?
请问以下工作?
// 1
int head = pq.peek();
pq.dequeue(head);
// 2
int head = pq.dequeue(pq.peek());
对于非基元类型,这种方法是否也适用?
答
Queue#peek
和Queue#element
回报队列的头值,Queue#poll
和Queue#remove
回报并删除它。
它看起来像
int head = pq.poll();
是你想要的。
而且:它只会只有适用于非基元值,因为队列将仅存储对象。诀窍是,(我猜)你的队列商店Integer
值和Java 1.5+可以自动将结果转换为int
基元(outboxing)。所以它感觉像队列存储的int
值。
+0
谢谢你的反对,但.. *为什么*? – 2010-12-20 10:11:13
答
peek()
- 回报,但不会删除水头值
poll()
- 返回和删除头部值
PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
pq.add(2);pq.add(3);
System.out.println(pq); // [2, 3]
System.out.println(pq.peek()); // head 2
System.out.println(pq); // 2 still exists. [2, 3]
System.out.println(pq.poll()); // 2. remove head (2)
System.out.println(pq); // [3]
护理开导我们,为什么你不想使用'民意调查()'? – falstro 2010-12-20 09:29:32
你从哪里找到'dequeue'方法? [我的API不显示](http://download.oracle.com/javase/6/docs/api/java/util/PriorityQueue.html)..? – 2010-12-20 09:33:59