Are there any differences between different methods in each of the following groups of element retrieve operations in LinkedList
?
Returning null + removing operations: poll()
, pollFirst()
.
Returning null + not removing operations: peek()
, peekFirst()
.
Throwing exception + removing operations: pop()
, remove()
, removeFirst()
.
Throwing exception + not removing operations: element()
, getFirst()
.
Similar duplications exists in insertion methods.
If there is no such difference, I would expect it to be mentioned in the javadoc of the methods (something like the good old "This is exactly like calling ..."). Is it only a sloppy documentation, or am I missing anything?
There is no difference between them, and it is listed in the documentation too, but you have to do some recursive searching to get there.
LinkedList
implements two interfaces - Queue
and Deque
. And Deque
extends from Queue
.
Now, Deque
has defined the method - Deque#pollFirst()
and inherited the method - Queue#poll()
.
So, LinkedList
has basically these two methods defined for the two interfaces it implements.
And about the similarity between those two methods, it is listed in documentation of Deque
as:
This interface extends the Queue interface. When a deque is used as a queue, FIFO (First-In-First-Out) behavior results. Elements are added at the end of the deque and removed from the beginning. The methods inherited from the Queue interface are precisely equivalent to Deque methods as indicated in the following table:
And there is a table listing the methods of Queue
class and the equivalent Deque
method. See Deque#poll()
, Deque#peek()
for e.g. They clearly list the equivalent method.
Your right it's bad documentation or something.
peek() Retrieves, but does not remove, the head (first element) of this list.
peekFirst() Retrieves, but does not remove, the first element of this list, or returns null if this list is empty.
This is what it says and I'm read here in my Java book that the head is the first item in a list.
The difference between them is version they were released with and the interfaces that LinkedList implements.
Example based on poll()
and pollFirst()
:
LinkedList
was released along with Java 1.2.
Since 1.5 LinkedList implements the Queue interface, which has
public E poll()
Since 1.6 LinkedList implements the Deque interface, which has
public E pollFirst()
edit:
It is important to keep the older implementation due to a backward compatibility.
来源:https://stackoverflow.com/questions/14851367/java-linkedlist-differences-between-retrieve-operations