Reputation: 2579
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?
Upvotes: 11
Views: 7204
Reputation: 299218
In Java 1.6, LinkedList
implements Deque
(Double-ended Queue). From the Deque.element()
javadocs:
Retrieves, but does not remove, the head of the queue represented by this deque (in other words, the first element of this deque). This method differs from peek only in that it throws an exception if this deque is empty.
This method is equivalent to
getFirst()
.
In Java 1.5, LinkedList
has both methods, but getFirst()
is not backed by an interface. My guess is that in Java 1.6 they implemented Deque
intentionally to include this method.
In Java 1.4, LinkedList
only has the getFirst()
, but it isn't backed by an interface.
Obviously I'd say this is an issue of maintaining backwards compatibility:
LinkedList
1.4 has getFirst() and
only the List
interfaceLinkedList
1.5 implements Queue
and hence needs to support the equivalent elements()
methodLinkedList
1.6 implements Deque
but because a) it has to remain backwards compatible and b) by policy, all methods should be backed by interfaces, the Deque
interface also includes the duplicate methodUpvotes: 3
Reputation: 354874
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.
Upvotes: 8
Reputation: 48615
In a link listed it looks like those are the same. But in a Queue, element()
seems to be a method to peak at the first element in the queue, but not remove it from the queue.
Upvotes: 0