对于java中的linkedlist,poll()和pop()之间的区别是什么?

Min*_*aaa 8 java stack linked-list

我最近发现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("");
Run Code Online (Sandbox Code Playgroud)

谢谢!!!

Mic*_*cky 27

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

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


dim*_*414 6

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

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);
}
Run Code Online (Sandbox Code Playgroud)

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.

  • 每个人都有自己的看法,但我想你会发现在这一点上你是少数。Null 及其引起的微妙且意外的行为被称为“[数十亿美元的错误](https://github.com/google/guava/wiki/UsingAndAvoidingNullExplained)”。异常提供了清晰的故障、明显的堆栈跟踪,并且通常使捕获逻辑错误变得更容易。 (2认同)