java java中链表的poll()和pop()有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35547237/
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-03 00:15:41  来源:igfitidea点击:

whats the difference between poll() and pop() for linkedlist in java?

javalinked-liststack

提问by Mingyaaa

I recently found there are two similar methods for linkedlist in java API, they all delete the first node and return it. I wrote the following codes to test and they did exactly same thing.Do they really work exactly same?

我最近发现java API中有两个类似的链表方法,它们都是删除第一个节点并返回它。我写了下面的代码来测试,他们做了完全一样的事情。他们真的工作完全一样吗?

    test.add(1);
    test.add(2);
    test.add(3);
    System.out.println(test.pop());
    for(int i = 0; i < test.size();i++ ){
        System.out.print(test.get(i) + " ");
    }
    System.out.println("");
    System.out.println(test.poll());
    for(int i = 0; i < test.size();i++ ){
        System.out.print(test.get(i) + " ");
    }
    System.out.println("");

Thanks!!!

谢谢!!!

回答by Michal Frystacky

Returning null + removing operations: poll()docs

返回 null + 删除操作:poll()docs

Throwing exception + removing operations: pop()docs

抛出异常 + 删除操作:pop()文档

回答by dimo414

They're functionally equivalent (save for how they handle the empty-list case), but you get both variants because LinkedListis an implementation of both a queue and a stack (namely Queueand Deque).

它们在功能上是等效的(除了它们如何处理空列表的情况),但是您会得到两种变体,因为LinkedList是队列和堆栈(即QueueDeque)的实现。

You can see their implementations in the source code:

你可以在源代码中看到它们的实现:

public E poll() {
    final Node<E> f = first;
    return (f == null) ? null : unlinkFirst(f);
}

public E pop() {
    return removeFirst();
}

public E removeFirst() {
    final Node<E> f = first;
    if (f == null)
        throw new NoSuchElementException();
    return unlinkFirst(f);
}

So poll()returns null if the list is empty, and pop()(and removeFirst()) raises a NoSuchElementException. This makes pop()a slightly nicer method to use, since you don't have to deal with nulls.

因此,poll()如果列表为空,则返回 null,并且pop()(and removeFirst()) 引发 a NoSuchElementException。这使得pop()使用稍微好一点的方法,因为您不必处理空值。