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("");
谢谢!!!
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);
}
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.
| 归档时间: | 
 | 
| 查看次数: | 14593 次 | 
| 最近记录: |