Java LinkedList - differences between retrieve operations

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-29 00:28:27

问题


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?


回答1:


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.




回答2:


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.




回答3:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!