我最近发现在java API中有两个类似的linkedlist方法,它们都删除第一个节点并返回它。我写了下面的代码来测试,它们做的是完全一样的thing.Do,它们的工作原理是完全一样的吗?
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("");
谢谢!
发布于 2016-02-22 14:45:04
它们在功能上是等价的(除了处理空列表的方式之外),但是您可以获得这两种变体,因为LinkedList
是队列和堆栈(即Queue
和Deque
)的实现。
您可以在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);
}
因此,如果列表为空,poll()
将返回null,而pop()
(和removeFirst()
)将引发NoSuchElementException
。这使得pop()
成为一种稍微好用的方法,因为您不必处理空值。
https://stackoverflow.com/questions/35547237
复制相似问题