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?
getFirst() method is used to fetch or retrieve the first element from a LinkedList or the element present at the head of the List.
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.
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.
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