假设我正在使用Java.util中的PriorityQueue类。我想从PriorityQueue pq中删除最大的数字,我们假设它位于队列的首位。
以下是否有效?
// 1
int head = pq.peek();
pq.dequeue(head);
// 2
int head = pq.dequeue(pq.peek());
对于非基元也是如此吗?
答案 0 :(得分:8)
Queue#peek
和Queue#element
返回队列的头部值,Queue#poll
和Queue#remove
返回并删除。
看起来像是
int head = pq.poll();
是你想要的。
并且:仅对非原始值起作用,因为队列只存储对象。诀窍是,(我猜)你的队列存储Integer
值,Java 1.5+可以自动将结果转换为int
基元(发件箱)。所以它感觉就像存储int
值的队列一样。
答案 1 :(得分:4)
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]