offerFirst(E e) method of Deque Interface in Java.

offerFirst(E e) method of Deque Interface in Java.


Posted in : Core Java Posted on : February 5, 2011 at 4:59 PM Comments : [ 0 ]

boolean offerFirst(E e) This method inserts an element at the front into a deque and returns 'true' if element is added to a deque otherwise returns false.

offerFirst(E e) method of Deque Interface in Java.

In this section we will discuss how can offerFirst(E e) method be implemented in Deque interface in java.

Syntax

boolean offerFirst(E e)

This method inserts an element at the front into a deque and returns 'true' if element is added to a deque otherwise returns false.

In this method you can insert a specified element at the front of the underlying deque. This method is preferably used when we are restricted with the capacity of deque. It inserts an element to the underlying deque if it is possible to do so instantly without breaking the capacity limitation of the deque. The addFirst(E e) method is different from this method only by their behavior, the offerFirst(E e) method throws exceptions as well as returns 'false' if insertion of an element in deque gets fail whereas addFirst(E e) method can only throws an exception.

Parameter description

e : It takes an element what do you want to insert at the front into a deque.

Example of offerFirst(E e) method

In this example we will show you how does an offerFirst(E e) method work in Deque interface. Through this example we will show how can you add a specified element at the front into Deque, and count the total number of elements of deque before and after adding the elements and the returned value of this method depending upon the operation. 

Example :

package devmanuals.com;
import java.util.Deque;
import java.util.LinkedList;
public class DequeOfferFirst {
  public static void main(String[] args) {
    Deque<String> dq = new LinkedList<String>();
    dq.offer("is");
    dq.offer("a");
    dq.offer("boy");
    System.out.println("The elements of Deque are : "+ dq);
    System.out.println("And the size of deque : " + dq.size());
    System.out.println("Now insert a new element at the front 'He'");
    boolean b = dq.offerFirst("He");
    System.out.println("Then the new Elements of deque are : " + dq);
    System.out.println("Inserts the specified element : " + b);
    System.out.println("And the size of new deque = " + dq.size());
  }
}

Output :

The elements of Deque are : [is, a, boy]

And the size of deque : 3

Now insert a new element at the front 'He'

Then the new Elements of deque are : [He, is, a, boy]

Inserts the specified element : true

And the size of new deque = 4

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics