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?
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!!!
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.
Returning null + removing operations: poll()
docs
Throwing exception + removing operations: pop()
docs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With