I was checking Java.util.LinkedList
class and found that Linked List class offers several methods
public void addFirst(E e)
public boolean offerFirst(E e)
public void push(E e)
All these 3 methods add an element to the head of the list. So why does different implementation require for the same function?
Is it because push is meant for Stack and
offerFirst – Dequeue
addFirst – LinkedList
or some other fundamentals?
Please share some insight here. Thanks
These are implemented in LinkedList
due to the contract of Deque
interface.
And the javadocs for Deque
clearly explain the difference:
void addFirst(E e)
Inserts the specified element at the front of this deque if it is possible to do so immediately without violating capacity restrictions. When using a capacity-restricted deque, it is generally preferable to use method offerFirst(E).
boolean offerFirst(E e)
Inserts the specified element at the front of this deque unless it would violate capacity restrictions. When using a capacity-restricted deque, this method is generally preferable to the addFirst(E) method, which can fail to insert an element only by throwing an exception.
The ArrayBlockingQueue
class (javadocs) is an example of a bounded queue implementation that implements Deque
.
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