Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LinkedList offers several methods for the same function- Why? [duplicate]

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

like image 433
inityk Avatar asked Dec 01 '15 07:12

inityk


1 Answers

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.

like image 53
Codebender Avatar answered Oct 17 '22 21:10

Codebender