7

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

inityk
  • 476
  • 1
  • 9
  • 18

2 Answers2

2

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.

Community
  • 1
  • 1
Codebender
  • 14,221
  • 7
  • 48
  • 85
0

Spend a look ad the java docs..

public void addFirst(E e) 
// Inserts the specified element at the beginning of this list.

public boolean offerFirst(E e)
// Inserts the specified element at the front of this list.

public void push(E e)
// Pushes an element onto the stack represented by this list.

For more infos: LinkedList

Deepika S
  • 3
  • 2
JoGe
  • 872
  • 10
  • 26
  • `public void addFirst(E e)` Inserts the specified element at the beginning of this list. Specified by: addFirst in interface **Deque** Parameters: e - the element to add `public boolean offerFirst(E e)` Inserts the specified element at the front of this list. Specified by: offerFirst in interface **Deque** Parameters: e - the element to insert Returns: true (as specified by Deque.offerFirst(E)) It seems same to me! There isn't any information about exception thrown. – inityk Dec 01 '15 at 07:54