I am trying to understand, why do we need Offer
and OfferLast
methods in Deque
, as both these methods add the elements at the end/tail of the Deque
. What is the significance of it?
The Queue interface was added in Java 5. It defined the offer
method, which adds an element at the end.
(The offer
method and the add
method both return booleans. They differ in that add
is permitted to reject the element and return false only if the element is already present in the collection. The offer
method can reject the element for other reasons, such as the queue being full.)
With Queue.offer
, there is little question about the semantics, as elements are generally added to the tail of a queue and removed from the head.
The Deque interface was added in Java 6. A deque allows elements to be added to and removed from both the head and tail, so Deque
defines offerFirst
and offerLast
methods. A deque is also a queue, so Deque
is a sub-interface of Queue
. Thus it inherits the offer
method from Queue
. That's how Deque
ends up with both offer
and offerLast
.
We probably could have gotten by without adding offerLast
, but that would have left asymmetries in the Deque
interface. Many operations work on both the head and the tail (add, get, offer, peek, poll, remove) so it makes sense for all of them to have -first and -last variants, even though this adds redundancy. This redundancy occurs with other Queue
methods as well, such as add
and addLast
, peek
and peekFirst
, poll
and pollFirst
, and remove
and removeFirst
.