java Queue 接口中的 peek() 方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29554308/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 15:30:13  来源:igfitidea点击:

peek() method in Queue interface

javascjp

提问by kittu

From Java documentation:

Java 文档

The remove() and poll() methods remove and return the head of the queue.

The element() and peek() methods return, but do not remove, the head of the queue.

remove() 和 poll() 方法移除并返回队列的头部。

element() 和 peek() 方法返回但不移除队列的头部。

From the second point it says method peek()returns head element of queue then how come its not returning head element of queue in the following program?

从第二点开始,它说方法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
}
}

Once the first element(carrot) is removed, apple becomes the head of queue(according to FIFO in queue) so peek()method should return apple right?

一旦第一个元素(胡萝卜)被移除,苹果就成为队列的头(根据队列中的先进先出)所以 peek() 方法应该返回苹果吗?

Example2:

示例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
}
}

回答by Aniket Thakur

Because you are polling first

因为你先投票

System.out.println(pq.poll() + ":" + pq.peek());

As it is a priority queue elements are stored as

因为它是一个优先级队列元素被存储为

carrot -> banana -> apple

When you poll()you get appleand is removed from queue. After which head of queue is bananawhich is exactly what you get when you peek().

当您poll()获得apple并从队列中删除时。在哪个队列头之后,banana这正是您在peek().

please look at the example 2 in updated question. Sorting is strange

请查看更新问题中的示例 2。排序很奇怪

It's just what you don't expect. You can see the documentation

这只是你没想到的。你可以看文档

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()).

方法 iterator() 中提供的 Iterator 不保证以任何特定顺序遍历优先级队列的元素。如果您需要有序遍历,请考虑使用 Arrays.sort(pq.toArray())。

You will understand this better if you read priority heap data structure which java priority queue use. You should use poll(), peek()methods to get ordered data.

如果您阅读 Java 优先级队列使用的优先级堆数据结构,您将更好地理解这一点。您应该使用poll(), peek()方法来获取有序数据。

回答by Balaji Katika

You are using PriorityQueue and not java.util.Queue (Regular Queue) PriorityQueue sorts the elements depending on the implementation of the Comparable::compareTo() method which is a natural ordering (alphabetical order) for String.class.

您使用的是 PriorityQueue 而不是 java.util.Queue(常规队列) PriorityQueue 根据 Comparable::compareTo() 方法的实现对元素进行排序,该方法是 String.class 的自然排序(字母顺序)。

Hence, the elements in your queue would be apple-banana-carrot. The output is as expected

因此,您队列中的元素将是 apple-banana-carrot。输出符合预期

回答by APD

You have answered the question yourself by quoting the documentation.

您已经通过引用文档自己回答了这个问题。

Your priority queue contains

您的优先队列包含

apple, banana, carrot

pollreturns "apple" then removes it. So the queue is now

poll返回“apple”然后将其删除。所以队列现在是

banana, carrot

peekthen returns "banana"

peek然后返回“香蕉”

回答by niks

POLL() method will remove that element from queue and return element to calling method. PEEK() method will only return that element. refer this implementation code of POLL() and PEEK() method:

POLL() 方法将从队列中删除该元素并将元素返回给调用方法。PEEK() 方法将只返回该元素。参考这个 POLL() 和 PEEK() 方法的实现代码:

public E poll() {
        if (this.size == 0)
            return null;
        int i = --this.size;
        this.modCount += 1;
        Object localObject1 = this.queue[0];
        Object localObject2 = this.queue[i];
        this.queue[i] = null; 
        if (i != 0)
            siftDown(0, localObject2);
        return localObject1;
}

public E peek() {
        return ((this.size == 0) ? null : this.queue[0]);
}

回答by dinesh kandpal

The Queue interface defines some methods for acting on the first element of the list, which differ in the way they behave. These methods are:

Queue 接口定义了一些方法来处理列表的第一个元素,它们的行为方式不同。这些方法是:

peek()
element()
poll()
remove()

The peek()This method retrieves the value of the first element of the queue without removing it from the queue. For each invocation of the method we always get the same value and its execution does not affect the size of the queue. If the queue is empty the peek() method returns null.

peek()这个方法检索队列第一个元素的值,而不将它从队列中移除。对于方法的每次调用,我们总是得到相同的值,并且它的执行不会影响队列的大小。如果队列为空,peek() 方法返回 null。

The element()This method behaves like peek(), so it again retrieves the value of the first element without removing it. Unlike peek ), however, if the list is empty element() throws a NoSuchElementException.

element()此方法的行为类似于 peek(),因此它再次检索第一个元素的值而不删除它。但是,与 peek ) 不同的是,如果列表为空,则 element() 会抛出 NoSuchElementException。

The poll()This method retrieves the value of the first element of the queue by removing it from the queue. . At each invocation it removes the first element of the list and if the list is already empty it returns null but does not throw any exception.

poll()这个方法通过从队列中移除来检索队列第一个元素的值。. 在每次调用时,它删除列表的第一个元素,如果列表已经为空,则返回 null 但不抛出任何异常。

The remove()This method behaves as the poll() method, so it removes the first element of the list and if the list is empty it throws a NoSuchElementException

remove()此方法的行为与 poll() 方法相同,因此它删除列表的第一个元素,如果列表为空,则抛出 NoSuchElementException