【发布时间】:2015-04-10 05:53:53
【问题描述】:
remove() 和 poll() 方法删除并返回队列的头部。
element() 和 peek() 方法返回但不移除队列的头部。
从第二点开始,它说方法peek()返回队列的头元素,那么它为什么在下面的程序中不返回队列的头元素?
public class PQ {
public static void main(String[] args) {
PriorityQueue<String> pq = new PriorityQueue<String>();
pq.add("carrot");
pq.add("apple");
pq.add("banana");
System.out.println(pq.poll() + ":" + pq.peek()); // prints apple and banana rather than apple and apple
}
}
一旦第一个元素(胡萝卜)被删除,苹果就成为队列的头(根据队列中的FIFO)所以peek()方法应该返回苹果对吗?
示例2:
public class PQ {
public static void main(String[] args) {
PriorityQueue<String> pq = new PriorityQueue<String>();
pq.add("carrot");
pq.add("apple");
pq.add("banana");
System.out.println(pq); // prints [apple, carrot, banana] -> it should be [apple, banana, carrot] right? if it is following natural sorting order
}
}
【问题讨论】:
-
PriorityQueue对元素进行排序,这意味着您的队列的顺序是(头)apple、banana、carrot(尾)。因此,对poll()的调用将删除并返回头部(apple),使banana成为新的头部,如以下对peek()的调用所示。 -
所以
PriorityQueue不遵循FIFO? -
@kittu 正确;它遵循自然顺序。
-
@Vulcan 在
PriorityQueue比较的情况下,自然排序是否意味着字典顺序? -
是的自然排序顺序
lexicographical在字符串的情况下排序。