Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between the element() and getFirst() methods in the LinkedList class?

LinkedList has similar descriptions for the element() method and the getFirst() method (strangely - not the same words).

Deque clearly states that the two methods are the same in terms of the return value and the exception.

My question is - why have 2 identical methods? Is it for backward compatibility? Is one approach more efficient than the other?

like image 929
user183037 Avatar asked Feb 06 '11 19:02

user183037


People also ask

Which method is used to get the first element from a linked list?

getFirst() method is used to fetch or retrieve the first element from a LinkedList or the element present at the head of the List.

How do you initialize an empty linked list in Java?

Hence this class will have a reference to the Node type. The general syntax for this constructor is: LinkedList<type> linkedList = new LinkedList<>(); The above statement creates an empty LinkedList.


1 Answers

element() is inherited from Queue where it makes sense to have only one accessing method since all you can do in a queue is remove the first element. However, a deque supports this from both ends, necessitating explicit methods to do so.

And it's not very nice to design an API where you would access the first element with element() and the last with getLast().

Another thing that might play into this is that Deque was added in 1.6, where parts of the ancient parts of the Java Collections Framework have been obsoleted by newer conventions, such as explicit get~/set~ methods for property access. In that context, getFirst() and getLast more closely adhere to the current Java conventions.

like image 152
Joey Avatar answered Oct 13 '22 04:10

Joey